1

我曾尝试使用此代码:

$terms = get_terms('translates_category', 'include=220,238');

但它返回一个包含两个独立对象的数组:

Array
(
[0] => stdClass Object
    (
        [term_id] => 220
        [name] => Degrees of comparison
        [slug] => degrees-of-comparison
        [term_group] => 0
        [term_taxonomy_id] => 272
        [taxonomy] => translates_category
        [description] => 
        [parent] => 217
        [count] => 2
    )

[1] => stdClass Object
    (
        [term_id] => 238
        [name] => Lesson
        [slug] => lesson
        [term_group] => 0
        [term_taxonomy_id] => 290
        [taxonomy] => translates_category
        [description] => 
        [parent] => 0
        [count] => 1
    )
)

我可以假设,它分别返回这两个类别中所有帖子的数量(计数)。但我只需要同时位于两个类别中的帖子的总数。

第一个类别可能有 100 个帖子,第二个类别可能有 10 个帖子,但一次可能只有一个帖子与这两个类别相关联。我需要计算这些帖子。

我怎样才能做到这一点?

4

3 回答 3

3

这应该可以解决您的问题:

function my_post_count($tax, $cat1, $cat2) {
    $args = array(
        'tax_query' => array(
            'relation' => 'AND',
            array(
                'taxonomy' => $tax,
                'field' => 'term_taxonomy_id',
                'terms' => array( $cat1 ),
                'operator' => 'IN'
            ),
            array(
                'taxonomy' => $tax,
                'field' => 'term_taxonomy_id',
                'terms' => array( $cat2 ),
                'operator' => 'IN'
            ),
        )
    );
    $query = new WP_Query( $args );
    return $query->post_count;
}
echo my_post_count('translates_category', 220, 238);
于 2012-09-26T12:45:45.750 回答
0

使用下面的代码,为此您必须为帖子制作两部分,即每个部分

<?php
global $post;
$args = array( 'numberposts' => 5, 'category' => 3 );


$myposts = get_posts( $args );
foreach( $myposts as $post ) :
setup_postdata($post); ?>

<?php the_title(); ?>
<?php the_content(); ?>

<?php endforeach; ?>

更改要显示的帖子数量和类别...

于 2012-09-26T12:01:31.887 回答
0

您可以将此功能粘贴到您的functions.php

function get_post_count($categories) {
    global $wpdb;
    $post_count = 0;
    $post_count_array=array();
    foreach($categories as $cat) :
        $catID=get_cat_id($cat);
        $querystr = "SELECT count FROM $wpdb->term_taxonomy WHERE term_id = $catID";
        $result = $wpdb->get_var($querystr);
        $post_count += $result;
        $post_count_array[$cat]=$result;
    endforeach;
    $post_count_array['total']=$post_count;
    return $post_count_array;
}

然后像这样调用这个函数

$posts_Cat_Num=get_post_count(array('plugin', 'php')); // these are category names
print_r($posts_Cat_Num); // Array ( [plugin] => 2 [php] => 3 [total] => 5 ) 
echo $posts_Cat_Num['plugin']; // 2
echo $posts_Cat_Num['php']; // 3
echo $posts_Cat_Num['total']; // 5

更新(从评论中我理解了这个问题)

$q=new WP_Query(array('category__and' => array(220, 238))); // get posts for both category ids
echo $q->post_count;
于 2012-09-26T12:21:39.330 回答