I write the following function to get the post data on publish post but i see that post_meta is not available, its always empty. How do i retrieve the post meta data of a post on publish_post hook?

The bottom line is i want to collect the data $article convert into json and post it using curl. When i convert it using print_r(json_encode($article)) it actually executes the html tags in the content and outputting. Is there any neat way to do it like how wp_send_json is doing?

add_action( 'publish_post', 'newdb',10,2);

function newdb($post_id, $post){

            if($post_id !=null){
            $article['postID'] = $post->ID;
            $article['seo_url'] = get_permalink($post->ID);
            $article['title'] = $post->post_title;
            $article['status'] = $post->post_status;
            $article['body'] = html_entity_decode(htmlentities(addslashes($post->post_content)));
            $article['related'] = array();
            $relatedStories = get_post_meta($post->ID, 'realtor_related_stories', true);
            if ($relatedStories != null) {
                $rsCount = count($relatedStories) - 1;
                while ($rsCount > 0) {
                    $rStories['title'] = $relatedStories['related_stories_attribution_' . $rsCount]['headline'];
                    $rStories['seo_url'] = $relatedStories['related_stories_attribution_' . $rsCount]['url'];
                    $rStories['img_src'] = wp_get_attachment_url(get_post_thumbnail_id(url_to_postid($rStories['seo_url'])));
                    array_push($article['related'], $rStories);
 $article['seo_focus_keyword'] = get_post_meta($post->ID, '_yoast_wpseo_focuskw', true);
            $article['seo_title'] = get_post_meta($post->ID, '_yoast_wpseo_title', true);
            $article['seo_metadesc'] = get_post_meta($post->ID, '_yoast_wpseo_metadesc', true);
//print_r($article) => gives wierd output because of embed tags in post body


If the wp_send_json() function is sending the right data, but for some reason you want to use another function to actually send the JSON data, then you can use wp_json_encode(). This is basically the only thing that wp_send_json() does before sending off the data.

add_action( 'publish_post', 'wpse_228607_publish_post', 10, 2 );
function wpse_228607_publish_post( $post_id, $post ){
  //* Do some stuff to get your $article variable

  $encode = wp_json_encode( $article );

  //* Do some stuff with the json encoded article

Make sure you're sending the correct Content-Type and charset. wp_send_json() takes care of that for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.