开发者

Wordpress loop export category list to php echo

Am a bit stuck with a wordpress loop, am wondering if anyone can help.

I need to run a Wordpress loop but only get the category names/id (Either开发者_如何学运维 is fine) from each post and have all of those variables as one php item I can echo later in the page.

Its for a category list filter system, but I only want to show categories which have posted displayed on that page.

The loop will be dynamic as well, so I cant just hard code exclude/include, I need to echo the value of all the numbers in together.

I hope that makes sense! Anyone who has any ideas would be really cool. Thanks!


I would use the get_the_category function like so...

<?php
// before you begin the wordpress loop
$category_array = array();
?>

<?php
// from *within* the wordpress loop
foreach((get_the_category()) as $category) { 
    if (!in_array($category->cat_name, $category_array)) {
        $category_array[] = $category->cat_name;
    }
}
?>

<?php
// after the wordpress loop is finished
echo implode(",", $category_array);
?>

This code basically creates a new (empty) array so that for each category in the current page, check if you've already added that category name to the array, then if not, go ahead and add it. Then when the loop is finished, echo out a comma separated string of category names. (You can of course, change the separator if you want a comma and space ", " or any other delimiter).

The Codex article has a lot more information on other things you can do with that function. Hope that helps.

Edit: Fixed the implementation because I forgot this was going to be used on a page where you are listing many posts using the loop. (You need to initialize your array from outside the wordpress loop, then echo your results after the loop has been finished).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜