WP:如果类别仅包含一个 post,则显示 post 而不是子类别
WP: Display post instead of Subcategory, if Category contains only one single post
我仍然对这些东西有疑问(是的,它仍然是我的第一个 WP 项目)..
如果该类别中有多个 post,我将显示类别及其描述。
但是,如果一个类别中只有一个 post,我需要直接向 post 显示 link。
这适用于(部分)以下代码,但前提是只有一个“1-post-category”。如果有多个它只显示一个(我猜是最新添加的)。所以一定是有什么地方错了或者漏了。我猜是一个循环......?如果有人能仔细看看就太好了 - 非常感谢!
<?php
foreach ( $categories as $category ) {
// If there is only one post available, go directly to the post
if($category->count == 1) {
$all_posts = get_posts($category);
echo '<div class="card"><div class="card-header"><h4>' . get_the_title($all_posts[0]->ID) . '</h4><div class="card-body">' . wp_trim_words( get_the_content($all_posts[0]->ID), 30, '...') . '</div><div class="card-footer"><a href="' . get_permalink($all_posts[0]->ID) . '" class="readmore">Read more</a></div></div></div>';
// otherwise display subcategories
} else {
echo '<div class="card"><div class="card-header"><h4>' . $category->name . '</h4><div class="card-body">' . wp_trim_words($category->description, 30, '...') . '</div><div class="card-footer"><a href="' . get_category_link( $category->term_id ) . '" class="readmore">Read more</a></div></div></div>';
}
}
?>
没有看到你的输出很难说,但我很确定这行:
$all_posts = get_posts($category)
并不像您想象的那样工作。相反,试试这个:
$all_posts = get_posts( array('category'=>$category->term_id) );
我仍然对这些东西有疑问(是的,它仍然是我的第一个 WP 项目)..
如果该类别中有多个 post,我将显示类别及其描述。 但是,如果一个类别中只有一个 post,我需要直接向 post 显示 link。 这适用于(部分)以下代码,但前提是只有一个“1-post-category”。如果有多个它只显示一个(我猜是最新添加的)。所以一定是有什么地方错了或者漏了。我猜是一个循环......?如果有人能仔细看看就太好了 - 非常感谢!
<?php
foreach ( $categories as $category ) {
// If there is only one post available, go directly to the post
if($category->count == 1) {
$all_posts = get_posts($category);
echo '<div class="card"><div class="card-header"><h4>' . get_the_title($all_posts[0]->ID) . '</h4><div class="card-body">' . wp_trim_words( get_the_content($all_posts[0]->ID), 30, '...') . '</div><div class="card-footer"><a href="' . get_permalink($all_posts[0]->ID) . '" class="readmore">Read more</a></div></div></div>';
// otherwise display subcategories
} else {
echo '<div class="card"><div class="card-header"><h4>' . $category->name . '</h4><div class="card-body">' . wp_trim_words($category->description, 30, '...') . '</div><div class="card-footer"><a href="' . get_category_link( $category->term_id ) . '" class="readmore">Read more</a></div></div></div>';
}
}
?>
没有看到你的输出很难说,但我很确定这行:
$all_posts = get_posts($category)
并不像您想象的那样工作。相反,试试这个:
$all_posts = get_posts( array('category'=>$category->term_id) );