Wordpress - Publish post with featured image at same time via PHP

I am publishing to Wordpress via PHP, as follows.

  • Create post with wp_insert_post()
  • Add Featured Image with wp_insert_attachment()

Problem :

When creating the Post, there is a Plugin (SNAP autoposter) that will automatically publish it on Facebook. But, as obvious, it does not wait until the featured image is attached.

Question :

How should I proceed to publish the post with an already assigned attachment?

Thanks a lot for your help :)

Solutions

Don't publish the post until the attachment has been added.

  • Set the post_status to draft when you call wp_insert_post .
  • Add the attachment to the draft.
  • Use wp_publish_post to publish the post.

If the plugin is setup correctly, it will be listening for the status transition to publish.

Similar questions

Getting the Featured image URL and inserting it as Custom Field on Post update / publish
I've tried a number of solutions posted here regarding converting custom fields to featured images - of course in reverse; but non seem to work for me. What I'm trying to do is grab the Featured Image URL once the image is uploaded and set as a featured image; then automatically set the full size image URL as a custom field. This needs to work on b...
Get first URL from custom field, download and set as featured image on post publish
I have a plugin that is adding text and a URL to a custom field when the post is published (not saved as draft). I want to get/make a function or plugin to search within the custom field and sideload the image from a URL, then add that image as the featured image. Doing some searching I found this function from another StackExchange post that was d...
How do I stop concurrent PHP scripts from executing the same code at the same time?
I'm using a service for currency exchange rates which only allows 1000 requests a month, so I have to save the retrieved exchange rates to the database for an hour before updating them with a new request. However my website has been requesting new exchange rates far more frequently than every hour and I finally realized it's because of concurrent P...
Posts without featured image using other post's featured image
I am using the following code (see bottom) to display a custom post called 'artists'. I am also using <?php if (has_post_thumbnail( $post->ID ) ) so I can set the background of a div using the post thumbnail (I don't think this is the problem). I want to display all of the posts on one page so use 'numberposts' => -1,. I have noticed that ...

Also ask

We use cookies to deliver the best possible experience on our website. By continuing to use this site, accepting or closing this box, you consent to our use of cookies. To learn more, visit our privacy policy .