正在寻找使用自定义字段将旧帖子推送到WP\\u查询中的方法。例如,我今年有10篇文章,想将过去的2篇文章重新发布到自定义rss提要。
因此,对于旧帖子,必须按照帖子日期和帖子元中的值对帖子进行排序:
new post - (post date: 2018-11-11)
new post - (post date: 2018-11-10)
old post - (post date: 2017-05-01, post-meta date: 2018-11-09)
new post - (post date: 2018-11-08)
我尝试在WP\\u查询中按2个值排序,但它不起作用
<?php
add_filter(\'pre_get_posts\', function($query) {
if($query->is_main_query() && $query->is_feed()) {
$query->set(\'posts_per_rss\', 3);
$query->set(\'post_type\', \'post\');
$query->set(\'post_status\', \'publish\');
$query->set(\'meta_query\', [
\'relation\' => \'OR\',
\'push_clause\' => [
\'key\' => \'is-push\',
\'compare\' => \'EXISTS\'
],
\'exclude_clause\' => [
\'key\' => \'is-exclude\',
\'compare\' => \'NOT EXISTS\'
]
]);
$query->set(\'orderby\', [\'push_clause\' => \'DESC\']);
}
});
是否有任何方法可以使用WP\\u查询实现此功能?
Update:我已经编写了纯sql查询,可以根据需要进行排序
SELECT SQL_CALC_FOUND_ROWS wp_posts.post_title, wp_posts.post_date, m.*, IFNULL(m.meta_value, wp_posts.post_date) as d
FROM wp_posts
LEFT JOIN wp_postmeta m ON (wp_posts.ID = m.post_id AND m.meta_key = \'is-push\')
WHERE wp_posts.post_status = \'publish\' AND wp_posts.post_type = \'post\'
ORDER BY
d DESC
LIMIT 10
最合适的回答,由SO网友:Anton Lukin 整理而成
最后,我决定使用带有get\\u results方法的自定义sql查询。
$query = "SELECT SQL_CALC_FOUND_ROWS p.*, IFNULL(m2.meta_value, p.post_date_gmt) as zen_date
FROM {$wpdb->posts} p
LEFT JOIN {$wpdb->postmeta} m1 ON (p.ID = m1.post_id AND m1.meta_key = \'is-exclude\')
LEFT JOIN {$wpdb->postmeta} m2 ON (p.ID = m2.post_id AND m2.meta_key = \'is-push\')
WHERE p.post_type = \'post\' AND p.post_status = \'publish\' AND m1.post_id IS NULL
GROUP BY p.ID ORDER BY zen_date DESC LIMIT 0, 50";
$posts = $wpdb->get_results($query, OBJECT);
foreach($posts as $post) {
setup_postdata($post);
// do something
}
如果有人提出更好的建议,我很乐意接受这个答案。