【问题标题】:How to get the tags on publish the post in all cases?如何在所有情况下获取发布帖子的标签?
【发布时间】:2019-12-03 04:33:54
【问题描述】:

要求:在每个发布/更新帖子上,我们需要来自的所有标签 发布并在上面做一些功能。

案例 1: 创建帖子,添加标签并立即发布 === 完美运行 ===

案例 2: 更新旧帖子并点击更新按钮。 === 完美运行 ===

案例 3: 创建帖子,添加标签并将其保存到草稿并关闭..再次打开同一个帖子并点击发布而不更改任何内容 === 失败 === 帖子结果中没有任何内容.. 未找到标签,但帖子中已有标签, 但是如果我们改变一些东西或者只是删除并添加相同的标签,那么它就可以工作。

我希望第 3 种情况能够正常工作。如何在发布时获取草稿帖子的标签。

下面是我的代码

// 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
    }
}

【问题讨论】:

  • 请停止滥用报价格式。这是为了当您实际引用某人或某事时,不是让您的文字“看起来更丰富多彩”......

标签: php wordpress tags


【解决方案1】:

找到解决方案

如果request_body中没有数据,我们也可以从已有的postID中获取。

更改代码:如果数据不可用,则添加条件,然后从帖子 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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    相关资源
    最近更新 更多