我想在每个类别的帖子标题后添加数字

时间:2021-03-27 作者:Guruh

enter image description here

有一个名为“自动编号帖子”的插件,其功能是在帖子标题旁边添加一个数字,但该插件的缺点是它不按类别排序。我希望每个类别的帖子都有自己的编号顺序。

add_action(\'the_title\', \'dk_auto_numbering\');
function dk_auto_numbering($title)
{
    $post_ID = get_the_ID();
    $the_post = get_post($post_ID);
    $date = $the_post->post_date;
    $maintitle = $the_post->post_title;
    $count = \'\';
    if ($the_post->post_status == \'publish\' and $the_post->post_type == \'post\' and in_the_loop()) {
        global $wpdb;
        $count = $wpdb->get_var("SELECT count(*) FROM $wpdb->posts  WHERE post_status=\'publish\' AND post_type=\'post\' AND post_date<\'{$date}\'");
        if ($maintitle == $title) {
            $count = $count . \'\';
            $title = $title . \' – Chapter \';
        } else {
            $count = \'\';
        }
    }
    return $title . $count;
} 

1 个回复
最合适的回答,由SO网友:Rup 整理而成

这里有一个未经测试的代码编辑,可以使用文章在计数中的第一个类别:

add_action(\'the_title\', \'dk_auto_numbering\');
function dk_auto_numbering($title)
{
    $post_ID = get_the_ID();
    $the_post = get_post($post_ID);
    $date = $the_post->post_date;
    $maintitle = $the_post->post_title;
    if ($maintitle == $title && $the_post->post_status == \'publish\' &&
        $the_post->post_type == \'post\' && in_the_loop()) {
        $categories = get_the_category($post_ID);
        if (is_array($categories) && count($categories) >= 1) {
            $first_category_id = $categories[0]->term_id;

            global $wpdb;
            $count = $wpdb->get_var(
                $wpdb->prepare("SELECT count(*) FROM $wpdb->posts AS p " .
                    "INNER JOIN $wpdb->term_relationships AS tr ON tr.object_id = p.id AND tr.term_taxonomy_id = %d " .
                    "WHERE post_status=\'publish\' AND post_type=\'post\' AND post_date <= %s", $first_category_id, $date)
            );

            if (isset($count)) {
                return $title . \' – Chapter \' . $count;
            }
        }
    }
    return $title;
}
我已经将has-something-has-something-has-something-has-something-modified-the-title-check-out移到了顶层,以便在数据库查询之前运行它,再加上一些其他小的重新安排。这有点不对称,因为它使用了当前帖子的第一个类别,但统计了所有早期包含该类别的帖子,但希望这足以满足您的需要:如果您需要更复杂的类别处理,可以编辑SQL。

正如我在最初的评论中所说,尽管我认为这些计数应该预先计算并缓存在post meta中的帖子,而不是作为页面上显示的每个帖子标题的单独查询运行。