how to add posts with image programmatically in wordpress

This the code to add a post programmatically in wordpress

require(dirname(__FILE__) . '/wp-load.php');

global $user_ID;

$new_post = array(
    'post_title' => 'Table Tennis',
    'post_content' => 'Table tennis or ping-pong is a sport in which two or four players hit a lightweight ball back and forth using a table tennis racket. The game takes place on a hard table divided by a net. Except for the initial serve, players must allow a ball played toward them only one bounce on their side of the table and must return it so that it bounces on the opposite side. Points are scored when a player fails to return the ball within the rules.',
    'post_status' => 'publish',
    'post_date' => date('Y-m-d H:i:s'),
    'post_author' => $user_ID,
    'post_type' => 'post',
    'post_category' => array(2),
);

$post_id = wp_insert_post($new_post);

how to add image to the post?

Read More

i am new to wordpress,thanks in advance..

Related posts

Leave a Reply

1 comment

  1. This will upload the file using WordPress and then insert it on the post as a featured image.

    $wp_filetype = wp_check_filetype($filename, null);
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => $filename,
        'post_content' => '',
        'post_status' => 'inherit'
    );
    
    $attach_id = wp_insert_attachment( $attachment, $thumbnail, $post_id );
    // you must first include the image.php file
    // for the function wp_generate_attachment_metadata() to work
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attach_data = wp_generate_attachment_metadata( $attach_id, $thumbnail );
    wp_update_attachment_metadata( $attach_id, $attach_data );
    
    // add featured image to post
    add_post_meta($post_id, '_thumbnail_id', $attach_id);