1

Requirement: On the each publish/update post, we need all tags from the post and do some functionality on that.

Case 1: Create post, add tags and Publish immediately === WORKS PERFECT ===

Case 2: Update Old post and hit Update button. === WORKS PERFECT ===

Case 3: Create post, add tags and save it to draft and close.. again open the same post and just hit the publish without changing anything

=== FAIL === Nothing in the post result.. no tags found but tags already available in the post, but if we change something or just remove and add the same tag then it works.

I want 3rd case to be worked.. How to get the tags of drafted post on publish..

BELOW IS MY CODE

// This is hook which calls automatically on publish the post
add_action( 'publish_post', array($this, 'post_published_notification'), 10, 2 );

// The function calls on publish the post
public static function post_published_notification( $ID, $post ) 
{
    $request_body = file_get_contents('php://input');
    PostPublishNotification::saveDataInNotificationTable($ID,$request_body);
}


// We neen the tags here..
public static function saveDataInNotificationTable($ID,$request_body)
{
    $post_data = json_decode($request_body);

    // Here is nothing when I publish the drafted post. otherwise it works when I publish/update the new/old post
    var_dump($post_data);
    exit;

    $tags = $post_data->tags;

    if(isset($tags) && is_array($tags) && count($tags) > 0)
    {
       // SOME CODE
    }
}
1
  • You might play around with some other hooks such as transition_post_status or save_post.
    – WebElaine
    Commented Dec 3, 2019 at 15:51

1 Answer 1

0

Found Solution :

If there is no data in the request_body, the we can also fetch it from the postID which is already we have.

Changed Code: added condition if data not available, then get it from post id

public static function saveDataInNotificationTable($ID,$request_body)
{
    $post_data = json_decode($request_body);

    $tags = $post_data->tags;

    if($post_data == "" || $post_data == null)
    {
        $tags = get_the_tags($ID);
    }

    if(isset($tags) && is_array($tags) && count($tags) > 0)
    {
       // SOME CODE
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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