列出所有类别并计算其中的帖子数(WordPress)

时间:2018-09-10 12:36:48

标签: php wordpress loops categories

我已经编写了这个几乎可以正常工作的函数:

function all_animals() {
    $categories = get_categories(array(
        'echo'             => 0,
        'hide_empty'       => 0,
        'taxonomy'         => 'species',
        'hierarchical'     => 1,
        'show_count'       => 0,
        'depth'            => 0
    )); ?>

    <ul>

    <?php ob_start();

    foreach ($categories as $cat) {

        $cat_args = array(
            'posts_per_page'    => -1,
            'post_type'         => 'animal',
            'showposts'         => -1,
            'post_status'       => 'publish',
            'cat'               => $cat->cat_ID
        );
        $the_animals = new WP_Query($cat_args);
        $animal_count = $the_animals->post_count;
        ?>
        <li>
            <a href="<?php echo get_category_link( $cat->cat_ID ); ?>">
                <?php echo $cat->cat_name; ?>
                <span class="count"><?php echo $animal_count; ?></span>
            </a>
        </li>
        <?php 
    } 
    wp_reset_postdata(); 
    $animal_list = ob_get_clean();
    return $animal_list;
    echo '</ul>';
}

...然后在这样的页面模板上使用它:

echo all_animals();

问题:唯一不起作用的是$animal_count,它始终返回0。

我也尝试过...

global $wp_query; 
$animal_count = $wp_query->found_posts;

...但这没什么区别。

我该如何解决?

2 个答案:

答案 0 :(得分:0)

您可以使用

pos = {
    "x": 0, 
    "y": 0
}

while True:

    n = input()
    if not n:
        break

    direction,steps=n.split()
    if direction == "UP":
        pos["y"] += int(steps)
    elif direction == "DOWN":
        pos["y"] -= int(steps)
    elif direction == "LEFT":
        pos["x"] -= int(steps)
    elif direction == "RIGHT":
        pos["x"] += int(steps)
print (int(round((pos["x"]**2 + pos["y"]**2)**0.5)))

此处“ ID为类别ID

答案 1 :(得分:0)

该解决方案比我想象的要容易:

$animal_count = $the_animals->count;