我在循环中使用 foreach 和 setup_postdata 来显示帖子。 $args 按“post_in”排序,但输出以 SQL 中帖子 ID 的默认 DESC 顺序显示。
这是输出:
在参数之前
Array ( [0] => 229 [1] => 226 [2] => 228 [3] => 227 [4] => 225 )
参数之后
Array (
[post_type] => movies
[post_in] => Array (
[0] => 229
[1] => 226
[2] => 228
[3] => 227
[4] => 225
)
[orderby] => post_in
)
查询转储
string(275) "
SELECT SQL_CALC_FOUND_ROWS wpxc_posts.ID
FROM wpxc_posts
WHERE 1=1
AND wpxc_posts.post_type = 'movies'
AND (wpxc_posts.post_status = 'publish'
OR wpxc_posts.post_status = 'acf-disabled'
OR wpxc_posts.post_status = 'private')
ORDER
BY wpxc_posts.post_date DESC
LIMIT 0, 10"
实际序列
229
228
227
226
225
代码如下:
<?php
$postidsstring = get_field('post_ids_to_be_included');
$postidsarray = explode(", ",$postidsstring);
echo "Before args <br>";
print_r($postidsarray);
$args = array(
'post_type'=> 'movies',
'post_in' => $postidsarray,
'orderby' => 'post_in'
);
$myposts = get_posts($args);
?><br><?php
echo "After args <br>";
print_r($args);
echo "<br>Query dump<br>";
$query = new WP_Query($args);
var_dump($query->request);
echo "<br> Actual Sequence";
foreach ( $myposts as $post ) :
global $post;
setup_postdata( $post ); ?>
<li>
<?php echo get_the_ID(); ?>
</li>
<?php endforeach;
?>
请建议如何控制这种情况下的排序。
最佳答案
您可以在发布的查询中看到它不是按 ID 排序(甚至不是按 ID 进行过滤),而是按 post_date
排序:
ORDER BY wpxc_posts.post_date DESC
我认为问题是双下划线 - note that post_in
is not in the spec, whereas post__in
is. 。尝试使用这个:
$args = array(
'post_type'=> 'movies',
'post__in' => $postidsarray,
'orderby' => 'post__in'
);
关于php - Wordpress/SQL 中 Orderby 默认为 DESC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53144359/