我在函数中有一个自定义函数。从类别列表中排除特定类别的php:
function incomplete_cat_list() {
$first_time = 1;
foreach((get_the_category()) as $category) {
if ($category->cat_name != \'Category Name\') {
if ($first_time == 1) {
echo \'<a class="cat-list" href="\' . get_category_link(
$category->term_id ) . \'" title="\' . sprintf( __( "See all %s" ),
$category->name ) . \'" \' . \'>\' . $category->name.\'</a>\';
$first_time = 0;
}
else {
}
}
}
}
我想在每个循环的相关帖子中使用它,但我不知道如何做。。。以下是按标签或类别显示相关帖子的代码:
<?php
$max_articles = 4; // How many articles to display
echo \'<div id="related-articles" class="relatedposts"><h3>Related articles</h3>\';
$cnt = 0;
$article_tags = get_the_tags();
$tags_string = \'\';
if ($article_tags) {
foreach ($article_tags as $article_tag) {
$tags_string .= $article_tag->slug . \',\';
}
}
$tag_related_posts = get_posts(\'exclude=\' . $post->ID . \'&numberposts=\' . $max_articles . \'&tag=\' . $tags_string);
if ($tag_related_posts) {
foreach ($tag_related_posts as $related_post) {
$cnt++;
echo \'<div class="child-\' . $cnt . \'">\';
echo \'<a href="\' . get_permalink($related_post->ID) . \'">\';
echo get_the_post_thumbnail($related_post->ID);
echo $related_post->post_title . \'</a>\';
echo incomplete_cat_list;
echo \'</div>\';
}
}
// Only if there\'s not enough tag related articles,
// we add some from the same category
if ($cnt < $max_articles) {
$article_categories = get_the_category($post->ID);
$category_string = \'\';
foreach($article_categories as $category) {
$category_string .= $category->cat_ID . \',\';
}
$cat_related_posts = get_posts(\'exclude=\' . $post->ID . \'&numberposts=\' . $max_articles . \'&category=\' . $category_string);
if ($cat_related_posts) {
foreach ($cat_related_posts as $related_post) {
$cnt++;
if ($cnt > $max_articles) break;
echo \'<div class="child-\' . $cnt . \'">\';
echo \'<a href="\' . get_permalink($related_post->ID) . \'">\';
echo get_the_post_thumbnail($related_post->ID);
echo $related_post->post_title . \'</a>\';
echo incomplete_cat_list;
echo \'</div>\';
}
}
}
echo \'</div>\';
?>
How to call the custom function from functions.php inside above loop?
最合适的回答,由SO网友:Shibi 整理而成
首先,需要将post\\u id传递给此函数,以便在get_the_category($post_id)
function incomplete_cat_list($post_id = \'\') {
global $post;
$post_id = ($post_id) ? $post_id : $post->ID;
$first_time = 1;
$categories = get_the_category($post_id);
foreach($categories as $category) {
if ($category->cat_name != \'Category Name\') {
if ($first_time == 1) {
echo \'<a class="cat-list" href="\' . get_category_link(
$category->term_id ) . \'" title="\' . sprintf( __( "See all %s" ),
$category->name ) . \'" \' . \'>\' . $category->name.\'</a>\';
$first_time = 0;
}
else {
}
}
}
}
此函数已存在
echo
所以你不必再重复了。所以你应该这样称呼它。
incomplete_cat_list($related_post->ID);
如果您想在获得第一个类别后停止循环,而不是使用此
$first_time
仅使用变量
break;
停止循环。