我想按帖子元字段订购自定义帖子类型。此查询部分工作正常并加载结果。问题是每次执行此查询时,结果的顺序都不同。我在最后几页也找到了一些副本。你能帮我弄清楚那里发生了什么事吗?
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts
INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )
WHERE 1=1 AND wp_posts.post_type = \'estate_agent\' AND
((wp_posts.post_status = \'publish\')) AND
(wp_postmeta.meta_key = \'package_id\')
GROUP BY wp_posts.ID
ORDER BY wp_postmeta.meta_value+0 DESC LIMIT 0, 10
Updated实际上,我正在使用Wordpress方式运行上述查询。以上是Wordpress调试插件的原始查询输出。我真的很抱歉弄糊涂了。这就是我所尝试的。
$args = array(
\'post_type\' => \'estate_agent\',
\'post_status\' => \'publish\',
\'meta_key\' => \'package_id\',
\'orderby\' => \'meta_value_num\',
\'order\' => \'DESC\',
\'paged\' => $paged,
\'posts_per_page\' => 10,
\'cache_results\' => false,
);
$agent_selection = new WP_Query($args);
SO网友:Abhik
当您可以使用核心WordPress功能进行查询时,无需对数据库进行自定义查询,WP_Query. 这会让你开始。您可以根据需要将订单设置为“ASC”或“DESC”。
$agents = new WP_Query( array (
\'post_type\' => \'estate_agent\',
\'meta_key\' => \'package_id\',
\'orderby\' => \'meta_value_num\',
\'order\' => \'DESC\'
\'posts_per_page\' => 10,
)
);
if ( $agents->have_posts() ) {
while ( $agents->have_posts() ) {
$agents->the_post();
// Do your stuffs for each Agents here, Like:
printf( esc_html__( \'Package ID: %1$s\', \'textdomain\' ), get_post_meta ( get_the_ID(), \'package_id\', true ) );
}
} else {
// No Agents Found
}
wp_reset_postdata();