繁体   English   中英

在我的主页上,我想显示一个“新闻”部分,其中包含过去 30 天内标记为“新闻”的帖子。 如何?

[英]on my homepage I want to show a "news" section with posts tagged "news" from the last 30 days. How?

正如标题所说,在主页 (index.php) 中,我想为新闻添加一个部分,该部分由“新闻”标记的帖子填充,并且只显示过去 30 天的帖子。 如果在过去 30 天内没有发布任何帖子,则新闻部分为空并消失。

  • 我如何查询过去 30 天的那些帖子? 使用新的 WP_query 或 pre_get_posts 吗?

  • 如果没有新闻,我如何编写它以使该部分不显示? 我猜这足以在循环内部创建 div 而不是在外部使用

     if ( have_posts() ) : echo '<div class="newsdiv">','<ul>' while ( have_posts() ) : the_post('<li>','</li>'); // Display post content the_title('<h2 class="news">','</h2>'); the_thumbnail(); the_excerpt(); endwhile; echo '</ul>','</div>' endif; ?>

我很抱歉平庸的问题或错误,我正在尝试学习 wordpress 和 php。 如果您可以在答案中添加一些解释,这将使我更容易了解原因,而不仅仅是如何。

使用 WP_Query 添加下一个参数:

$args= array( 
  'date_query' => array(
    array(
      'after' => '-30 days',
      'column' => 'post_date',
    ),
  ),
);
$your_query = new WP_Query($args);

它将抓取过去 30 天的帖子post_type => 'post'

if($your_query->have_posts()) : 
  // Code to display your news
  while($your_query->have_posts()) : $your_query->the_post();
    // Single news
  endwhile; wp_reset_postdata();
else: 
  // No posts
endif;

像这样使用 WP_Query:

$args = array(
    'post_type' => 'posts',
    'posts_per_page' => 20,
    'date_query' => array(
        array(
            'after'  => '-30 days',
            'column' => 'post_date',
        ),
    ),
);

$loop = new WP_Query( $args );
if ( $loop->have_posts() ) :
    while ( $loop->have_posts() ) : $loop->the_post();
    
    // add your loop content here

    endwhile; 
    wp_reset_postdata(); 
    // Reset query incase we want to use another query on the same page
endif;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM