是否有人知道如何隐藏具有相同类别的帖子?
我有Post 1,Post 2,Post 3有相同的类别。我可以在我的主页上显示最新帖子(帖子1),并隐藏其他帖子(帖子2和帖子3)
答案 0 :(得分:0)
这样做的一种方法是有三个单独的wp_queries。
//Query 1
$args1 = array(
'cat' => '1',
'nopaging' => true,
'posts_per_page' => '1',
); $query_1 = new WP_Query( $args1 );
if ( $query_1->have_posts() ) {
while ( $query_1->have_posts() ) {
$query_1->the_post();
// put content here
}
} else {
// no posts found
}
wp_reset_postdata();
//Query 2
$args2 = array(
'cat' => '2',
'nopaging' => true,
'posts_per_page' => '1',
); $query_2 = new WP_Query( $args2 );
if ( $query_2->have_posts() ) {
while ( $query_2->have_posts() ) {
$query_2->the_post();
// put content here
}
} else {
// no posts found
}
wp_reset_postdata();
//Query 3
$args3 = array(
'cat' => '3',
'nopaging' => true,
'posts_per_page' => '1',
); $query_3 = new WP_Query( $args3 );
if ( $query_3->have_posts() ) {
while ( $query_3->have_posts() ) {
$query_3->the_post();
// put content here
}
} else {
// no posts found
}
wp_reset_postdata();
答案 1 :(得分:0)
<?php
$args = array(
'numberposts' => 1,
'offset' => 0,
'category' => 0,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'draft, publish, future, pending, private',
'suppress_filters' => true
);
// the query
$the_query = new WP_Query( $args );?>
<?php if ( $the_query->have_posts() ) : ?>
<!-- pagination here -->
<!-- the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php endwhile; ?>
<!-- end of the loop -->
<!-- pagination here -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
将您的类别ID添加到&#39;类别&#39;。 转而使用这些链接获取更多信息。 https://codex.wordpress.org/Class_Reference/WP_Query https://codex.wordpress.org/Function_Reference/wp_get_recent_posts
答案 2 :(得分:0)
您可以通过
pre_get_posts
挂钩更改主页查询来实现此目的。
以下是代码:
function txt_domain_get_distinct_post_id()
{
$post_ids = [];
//getting all non empty category
$categories = get_terms('category', array(
'orderby' => 'count',
'hide_empty' => 0,
));
foreach ($categories as $category)
{
$args = array(
'posts_per_page' => -1,
'category' => $category->term_id,
'exclude' => $post_ids,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish'
);
//getting post from a specific category
$postlist = get_posts($args);
foreach ($postlist as $post)
{
if (!in_array($post->ID, $post_ids))
{
//this will only select one post form each category
$post_ids[] = $post->ID;
break;
}
}
}
return $post_ids;
}
add_filter( 'pre_get_posts', 'txt_domain_filter_get_posts' );
function txt_domain_filter_get_posts($query)
{
if (is_home() && $query->is_main_query())
{
$post_ids = txt_domain_get_distinct_post_id();
$query->set('post__in', $post_ids);
}
return $query;
}
代码进入活动子主题(或主题)的function.php文件。或者也可以在任何插件php文件中。
<小时/> 参考: