输出来自特定父类别的每个子类别的最新帖子
问题描述:
我想从每个具有父类别的类别(子类别)输出最新帖子。父类别ID为54.输出来自特定父类别的每个子类别的最新帖子
例如,如果类别54下有7个子类别,则输出帖子的数量应该是7(每个子类别都是最新的)。我希望这是有道理的。
我目前的代码如下。在此阶段,此代码仅输出一个最新的帖子(1个子类别),该帖子具有最新的cat id = 54。如果你能告诉我如何修改这个,以便我可以从多个子类别获得更多最新帖子,那将是非常好的。
<?php
$categories = get_categories();
foreach ($categories as $category) {
$args = array(
'cat' => 54,
'post_type' => 'post',
'posts_per_page' => '1',
);
}
?>
<?php $query = new WP_Query($args); ?>
<?php if ($query->have_posts()) : ?>
<div class="container">
<?php while ($query->have_posts()) : $query->the_post(); ?>
<div class="box">
<article>
<p><?php foreach((get_the_category()) as $childcat) { if (cat_is_ancestor_of(54, $childcat)) { echo '<a href="'.get_category_link($childcat->cat_ID).'">'; echo $childcat->cat_name . '</a>'; }} ?></p>
<?php if (has_post_thumbnail()): ?><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('box-pic'); ?></a><?php endif; ?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title();?></a></h3>
</article>
</div>
<?php endwhile;?>
</div>
<?php endif; ?>
<?php wp_reset_query(); ?>
答
以下是你需要使用的逻辑,
$term_id = 54;
$taxonomy_name = 'category';
$term_children = get_term_children($term_id, $taxonomy_name);
echo '<ul>';
foreach ($term_children as $child) {
$term = get_term_by('id', $child, $taxonomy_name);
$args = array(
'cat' => $term->term_id,
'post_type' => 'post',
'posts_per_page' => '1',
);
$query = new WP_Query($args); ?>
<?php if ($query->have_posts()) : ?>
<div class="container">
<?php while ($query->have_posts()) : $query->the_post(); ?>
<div class="box">
<article>
<p><?php foreach((get_the_category()) as $childcat) { if (cat_is_ancestor_of(54, $childcat)) { echo '<a href="'.get_category_link($childcat->cat_ID).'">'; echo $childcat->cat_name . '</a>'; }} ?></p>
<?php if (has_post_thumbnail()): ?><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('box-pic'); ?></a><?php endif; ?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title();?></a>
</h3>
</article>
</div>
<?php endwhile;?>
</div>
<?php endif; ?>
<?php wp_reset_query();
}
echo '</ul>';
答
试试这个,
$term_id =54 ;
$term_children = get_term_children($term_id, $taxonomy);
$term_id = array();
foreach ($term_children as $child) {
$term = get_term_by('id', $child, $taxonomy);
$term_id[] = $term->term_id; //childern ids array.
}
传递$ term_id到tax_query。
$args = array(
'post_type' => $post_type,
'posts_per_page' => 7,
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => $term_id
)
)
);
$query = new WP_Query($args);
这会为你工作。
+0
感谢您的这一点,但你的代码没有输出任何东西。此外,可以更改子类别的数量。现在是7,但将来会或多或少。因此,我必须避免像7. 以防万一,如果没有误解,“posts_per_page”为“1”意味着只有一个最新的单个子类别的职位是正确的吗? 即使我上面的原始代码可以通过更改posts_per_page值来输出多个。 – Palmtree
谢谢Ashmed。这和我原来的代码一样。它只输出来自单个孩子类别的最新帖子。有超过1(目前7)类别,这些类别有他们的最新帖子。这意味着输出帖子的数量应该是7. – Palmtree
线程在此继续.. https://wordpress.org/support/topic/output-latest-posts-from-each-child-categories-of-particular-父类别/#后9072769 – Palmtree