简体   繁体   中英

PHP WP Insert Post

I'm struggling a bit to insert a post with the features I require.

include ('../wp-load.php');
            $my_post = array(
              'post_title'    => 'title' ,
              'post_content'  => 'some content',
              'post_status'   => 'publish',
              'post_author'   => 1,
              'post_category' => array(34,35),
              'tags_input' => array('tag1,tag2'),
              'the_post_thumbnail' => 526
            );

            // Insert the post into the database
            wp_insert_post( $my_post );

Question 1:

It's all working besides for 'the_post_thumbnail' => 526 - I was hoping that was going to attach the media item id (526) as the featured post image (obviously this isn't working). What is the correct way to do this?

Question 2:

Is there a way to get the URL of the post that is created?

Please try the following example that uses the functions set_post_thumbnail() and get_permalink() :

       $my_post = array(
          'post_title'    => 'title' ,
          'post_content'  => 'some content',
          'post_status'   => 'publish',
          'post_author'   => 1,
          'post_category' => array(34,35),
          'tags_input'    => array('tag1,tag2'),
        );

        // Insert the post into the database
        $pid = wp_insert_post( $my_post );

        if( is_wp_error( $pid ) )
        { 
            // Display error:
            echo $pid->get_error_message();
        }
        else
        {
           // Set featured image to inserted post:
            set_post_thumbnail( $pid, 526 );

           // Get permalink:
            $link = get_permalink( $pid );
        }

where we use is_wp_error() to make sure the insert was sucessful.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM