首页 > 解决方案 > 如何检索分配给当前正在编辑的帖子的最新类别?

问题描述

我需要在编辑时限制属于特定类别的帖子的帖子拼贴长度。所以我需要检查哪些类别已分配给正在编辑的帖子,并决定是否限制其帖子标题。

我使用“wp_insert_post_data”来完成这项工作

add_filter( 'wp_insert_post_data' , 'limit_title_length' , '99', 2 );

但是我发现从传递返回的类别$postarr是现有类别。不是最新的类别。因此,它不适用于新帖子或在编辑时更改类别。

$post_category = $postarr['post_category'];

我还检查get_the_category()了函数内部,如果类别分配发生变化,它也会返回现有类别,而不是最新类别。

到目前为止我的代码...

function limit_title_length( $data,  $postarr ) {
// set up variables like max length, category id to limit
...

// get post id, title and categories from $data and $postarr passed
    $title =  $data['post_title'];
    $id = $postarr['ID'];
    $post_category = $postarr['post_category'];

// check if the specified category exists in the categories assigned to this post
...

// process $title, reset $post_title in $data 
...
    $data['post_title'] =  $title;
    return $data;
}
add_filter( 'wp_insert_post_data' , 'limit_title_length' , '99', 2 );

wp_insert_post_data在后期发布的后期阶段着火。我希望从中获得最新的类别,$postarr['post_category']; 但我的情况并非如此。任何解决方案或替代方案?

标签: wordpresscategoriespublish

解决方案


所以要明确一点 - 您想确定添加到帖子中的最新类别吗?

如果是这种情况,您将很难这样做,因为 Wordpress 不会为添加的类别保存元数据。如果您足够熟练,您可以编写这样的函数并将数据保存在自定义表中。然后取回使用。

如果您知道要查找的类别的名称,可以使用has_category!.


推荐阅读