【问题标题】:Display query posts at random from multiple categories从多个类别中随机显示查询帖子
【发布时间】:2017-05-31 17:39:51
【问题描述】:

我希望我的 WP_Query 随机显示来自数组中列出的所有类别的总共六个帖子。

我编写的循环/查询仅显示数组中第一个类别(艺术)的帖子。

我做错了什么?

<div class="main-news">
			<!-- Define our WP Query Parameters -->
			<?php $the_query6 = new WP_Query(array('posts_per_page' => 6, 'category_name' => 'Art' , 'Technology', 'Fashion-Beauty')); ?>

			<!-- Start our WP Query -->
			<?php while ($the_query6 -> have_posts()) {
			 $the_query6 -> the_post(); ?>
				<div class="new-content">
				<!-- Display the Post Image with Hyperlink -->
					<div class="new-image"><?php the_post_thumbnail('fashion');?></div>
					<div class="new-content-excerpt">
					<!-- Display the Post Category Hyperlink -->
						<h5><?php 
						foreach((get_the_category()) as $category) {
						echo $category->cat_name . ' ';
						}
						?></h5>

						<!-- Display the Post Title with Hyperlink -->
						<h1><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h1>
					</div>
				
				</div>
				<!-- Repeat the process and reset once it hits the limit -->
			<?php } ?>
			<?php wp_reset_postdata(); ?>
		</div>

【问题讨论】:

  • 你试过用'category' =&gt; id_of_the_category替换'category_name' =&gt; 'Art' , 'Technology', 'Fashion-Beauty')(无论如何都是无效的)吗?
  • WP Codex 似乎认为 category_name 没问题。但我将尝试使用类别 ID。谢谢:)
  • 它应该是一个类别 slug 的数组('category_name' =&gt; array('art', 'technology', 'fashion-beauty'),你没有创建一个。

标签: php wordpress while-loop


【解决方案1】:

category 放入category IDs 的数组中似乎可以解决问题。

我使用了以下代码:

&lt;?php $the_query6 = new WP_Query(array('category__in' =&gt; array( 240, 243, 239, ),'posts_per_page' =&gt; 4)); ?&gt;

【讨论】:

  • 通过保留类别而不是使用数字标识符来改进您的答案。
【解决方案2】:

罪魁祸首如下:

<?php $the_query6 = new WP_Query(array(
    'posts_per_page' => 6, 
    'category_name' => 'Art', 
    'Technology', 
    'Fashion-Beauty')
); ?>

要提取属于不同类别的帖子,必须使用以下格式(read more about it on WordPress' documentation):

  • 以下类别之一的帖子:'category_name' =&gt; 'art,technology,fashion-beauty'
  • 两个类别的帖子:'category_name' =&gt; 'art+technology+fashion-beauty'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 2021-10-12
    • 2013-12-10
    • 2018-01-19
    • 1970-01-01
    相关资源
    最近更新 更多