How to get the post data which is being published on wordpress on publish_post hook?

I have written this code for using the post data which is being published on publish post hook but i don’t know how to get values of the post

add_action('publish_post','fetch_post');

function fetch_post()
{
    global $wpdb;
    $sqlCommand = "SELECT post_title, post_name FROM wp_posts WHERE post_type='post' AND post_status='publish' ORDER BY ID DESC LIMIT 1";
    $posts = $wpdb->get_results($sqlCommand);
    print_r($posts);

    $sqlCommand = "INSERT INTO testing (post_title,post_name) VALUES(%s,%s)";
    $wpdb->query($wpdb->prepare($sqlCommand,$posts[0]->post_title,$posts[0]->post_name));
}

This code gives me that post but when we update a post this function gets called again and it returns the last post but i want the post which is being updated or publish.

Read More

Thanks in advance.

Related posts

Leave a Reply

1 comment

  1. You can use the following instead of your code:

    <?php
    
    add_action('publish_post', 'fetch_post', 10, 2);
    function fetch_post($id, $post) {
        global $wpdb;
    
        $sqlCommand = "INSERT INTO testing (post_title,post_name) VALUES(%s,%s)";
        $wpdb->query($wpdb->prepare($sqlCommand, $post->post_title, $post->post_name));
    }
    
    ?>
    

    The significant change I made was that i’m now using the parameters that the publish_post hook sends to the called function. The first parameter is the published post ID, and the second parameter is the entire post object of the updated post.

    So this way we’re also avoiding the first query from the example code that you’ve submitted.