WordPress中的视图发布数

时间:2014-12-11 16:20:19

标签: wordpress wordpress-theming

我必须显示访客正在查看的邮政编号 例如

  Post 4 of 13 [Previous] [Next]

我已经计算了类别

中的总帖子数
$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;
}

但问题是我没有将帖子编号视为

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:1)

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

您也可以在任何分类中使用它,只需在函数中设置分类法

即可
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;

}