个性化阅读
专注于IT技术分析

WordPress中如何查看文章数量

我必须显示访客正在查看的帖子编号, 例如

  Post 4 of 13 [Previous] [Next]

我已经计算了类别中的总post

$post_cat = get_the_category( $post->ID );
if($post_cat) {

    $post_cat_id = $post_cat[0]->term_id;
    $cat_posts = get_category($post_cat_id);
    $total_posts = $cat_posts->category_count;
}

但是问题是我没有看到正在查看的帖子号码


#1


你需要抓住所有帖子(使用与主查询中相同的orderby参数)并找到正确的位置。

$all_posts = get_posts( array(
    'category' => $post_cat_id, 'posts_per_page' => -1
) );

$pos = 0;
if ( $all_posts ) foreach ( $all_posts as $all_post ) {
    $pos++;
    if ( $all_post->ID == $post->ID ) break;
}
echo 'position is: ' . $pos;

#2


如果帖子中有多个类别, 这是我使用的另一个版本。此代码将尝试使用父类别, 如果找不到, 它将使用第一个子类别。

你也可以将其与任何分类法一起使用, 只需在这样的函数中设置分类法

echo get_post_number( $taxonomy = 'my_taxonomy' );

这是功能

function get_post_number( $taxonomy = 'category' ) {

        $query_object   = get_queried_object();

        $terms =  wp_get_post_terms( $query_object->ID, $taxonomy ); 

        if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){

            foreach ( $terms as $term ) {
                if( $term->parent === 0 ) {
                    $parent[] = $term;
                }else{
                    $child[] = $term;
                }
            }       

            if( $parent ) {
                $term_name = $parent[0]->name;
                $term_id   = $parent[0]->term_id;
            }else{
                $term_name = $child[0]->name;
                $term_id   = $child[0]->term_id;
            } 

            $post_args = [ 
                'post_type'         => $query_object->post_type, 'fields'            => 'ids', 'posts_per_page'    => -1, 'order'             => 'ASC', 'tax_query'         => [
                    [
                        'taxonomy'  => $taxonomy, 'field'     => 'term_id', 'terms'     => $term_id, ], ], ];

            $q = get_posts( $post_args );

            $total_posts = count( $q );
            $post_number = array_search( $query_object->ID, $q ) + 1;

            $text = 'This is currently post #' . $post_number . ' of ' . $total_posts . ' posted in ' . $term_name;

        }

    return $text;

}
赞(0)
未经允许不得转载:srcmini » WordPress中如何查看文章数量

评论 抢沙发

评论前必须登录!