php - Is there a way to fire other plugin functions from wp_insert_post

I am creating new post using wp_insert_post inside function.php. All the posts are created fine. I use FS POSTER plugin to share published article on social automatically. When I created posts using wp_insert_post, FS POSTER does not share the post. But when I create and publish post manually, it will share the post automatically.

How to notify other plugins like fs poster or any other social share plugins when I create the post using wp_insert_post.

if I create post in function.php, with post status draft and then publish it using UI publish button, it will share automatically.

How to fix this, what I am missing here ?

Answer

Solution:

the plugin you use probably does not listen to newly created wp_insert_post and its related hook, I can only guess it only runs if wp_insert_post is called to update a record.

The thing is when you create a post in admin panel there are multiple actions that runs and you are not creating a database record when you hit save. when you type in the Post Title, this automatically creates a record in posts table with draft post_status and when you hit Save/Publish, you are actually updating the database record and not creating a new record that runs multiple action hooks.

On the other hand, wp_insert_post directly create a database record in a single action.

You can try something like setting the post status into a custom status,

i.e.

// Create a post, change the action hook or however you create the post
add_action('how-ever-you-invoke-post-creation', function() {
    $post = array(
        'post_title'        => 'My not so cool post',
        'post_type'         => 'post',
        'post_status'       => 'waiting'
    );
    $postID = wp_insert_post( $post );
});

the code above will create a posts record in your database and sets its post_status to waiting. just a note: you won't be able to see posts with custom post_status in admin dashboard

now, try publishing your post after its created using wp_after_insert_post

add_action('wp_after_insert_post', function( $postID, $post ) {

    if ( $post && $post->post_status === 'waiting') // only run if post status is waiting
        wp_publish_post( $post );

}, 10, 2);

If this still doesn't trigger your plugin related functionality, then they also did not listen for that wp_publish_post and all the related hooks that runs with it.

Your best bet would be to install query monitor and monitor the hooks that runs or dig in the plugin code yourself.

Source