【发布时间】:2016-01-04 12:02:50
【问题描述】:
这听起来有点奇怪,但是..
我有一个客户要求对帖子结果进行随机排序(简单易行)。但他们也希望能够选择要“精选”的帖子并出现在列表顶部,其他帖子排序随机在下面。
我尝试过使用以下循环:
<?php global $query_string; query_posts( $query_string . '&orderby=rand' );
if (have_posts()): while (have_posts()) : the_post(); ?>
<?php if (get_field('featured_listing') == 1):?>
list of featured posts
<?php endif ;?>
<?php if (get_field('featured_listing') != 1):?>
all the other posts posts
<?php endif ;?>
<?php endwhile; ?>
<?php endif; ?>
但是特色帖子和非特色帖子都是随机排序的。
然后我尝试创建两个查询:
<?php global $query_string; query_posts( $query_string . '&orderby=rand' );
if (have_posts()): while (have_posts()) : the_post(); ?>
<?php if (get_field('featured_listing') == 1):?>
list of featured posts
<?php endif ;?>
<?php endwhile; ?>
<?php endif; ?>
<?php
global $query_string;
query_posts( $query_string . '&orderby=rand' );
if (have_posts()): while (have_posts()) : the_post(); ?>
<?php if (get_field('featured_listing') != 1):?>
all the other posts posts
<?php endif ;?>
<?php endwhile; ?>
<?php endif; ?>
但是当页面加载时,它们仍然作为一个随机列表加载。如果您刷新页面几次,精选帖子会出现在列表顶部,但这并不是很好。
这是 ACF 问题还是我忽略了一些非常简单的问题?谁能指出我正确的方向吗?
【问题讨论】:
-
永远不要使用
query_posts()。它破坏了主要查询对象,进而破坏了依赖于主要查询对象的数千个其他功能。此外,您的一个查询正在破坏另一个查询。除了破坏东西之外,query_posts()真的很慢并且会重新运行查询,这会减慢您的页面速度,这意味着糟糕的 SEO 排名。我不知道您在哪个页面上使用它,但您始终可以使用pre_get_posts修改主查询的查询变量,或者如果您真的需要自定义查询,请使用WP_Query
标签: php wordpress advanced-custom-fields