我有两个小部件,一个显示News 而另一个则显示除新闻以外的所有内容(我们称之为第二个Blog). 博客部分当前工作正常。
这些新闻帖子要么被归类为In the News
或者自定义post metain-the-news
, 设置为1。需要注意的是,并不是所有的帖子都会定义自定义帖子元。
我面临的主要问题是,我需要根据帖子的分类方式来比较帖子的元数据。
I may need to do a custom database query for this behavior, at least for the News. 是否可以执行自定义查询并将其转换为标准WP\\U查询对象?
我尝试的内容查询News.
Problem: 仅显示类别75中具有in-the-news = 1
.
Desired result: 显示类别75中的所有帖子,无论in-the-news
, 以及类别外的任何其他职位in-the-news = 1
query_posts(array(
\'ignore_sticky_posts\' => true,
\'posts_per_page\' => 3,
\'cat\' => "75", // Only posts within category 75 (News)
// Including posts tagged to show "In the News"
\'meta_query\' => array(
\'relation\' => \'OR\',
array(
\'key\' => \'in-the-news\',
\'value\' => \'1\',
\'compare\' => \'=\',
),
array(
\'key\' => \'in-the-news\',
\'compare\' => \'NOT EXISTS\',
\'value\' => \'\',
),
)
));
以下是Blog:此查询似乎工作正常,显示了类别75以外的所有帖子,并使用隐藏帖子in-the-news = 1
.
query_posts(array(
\'ignore_sticky_posts\' => true,
\'posts_per_page\' => 3,
\'cat\' => "-75", // All posts EXCLUDING those in category 75 (News)
\'meta_query\' => array(
\'relation\' => \'OR\',
array(
\'key\' => \'in-the-news\',
\'value\' => \'0\',
\'compare\' => \'=\',
),
array(
\'key\' => \'in-the-news\',
\'compare\' => \'NOT EXISTS\',
\'value\' => \'\',
),
)
));
由于s_ha_dum
对于这些惊人的例子,这里是我使用的最后一个查询。这里的逻辑是,我们对post ID数组执行自定义MySQL查询,然后使用返回的ID执行标准WP\\U查询。Note: 这里的逻辑比原来的帖子要复杂一些。基本上,我们最初有“新闻”和“博客”。但现在我们也有“风险”。此外in-the-news
post meta已更改为show-in-blog
当我们反转功能时。我不能指望任何人从一开始就理解这一点的原因,因为即使是我也认为这很荒谬(但客户想要它,就这样吧!)
这是我对“博客”小部件的查询。“新闻”区域略有变化。我不确定是否可以清除查询。我也不确定在同一个查询中执行这么多选择是否是一个坏主意。
global $wpdb;
$query = // Splitting the SQL query to it\'s own code block for syntax highlighting!
<小时> SELECT `ID`
FROM {$wpdb->posts} posts
WHERE (
/* Exclude posts in News (94)
Ignore show-in-blog option for News here,
as News is displayed on the same page */
94 NOT IN (
SELECT `term_taxonomy_id`
FROM {$wpdb->term_relationships}
WHERE `object_id` = posts.`ID`
)
AND
/* Exclude posts in Risk (96),
But show Risk posts that have the postmeta "show-in-blog" */
(
96 NOT IN (
SELECT `term_taxonomy_id`
FROM {$wpdb->term_relationships}
WHERE `object_id` = posts.`ID`
)
OR
(
96 IN (
SELECT `term_taxonomy_id`
FROM {$wpdb->term_relationships}
WHERE `object_id` = posts.`ID`
)
AND
1 IN (
SELECT `meta_value`
FROM {$wpdb->postmeta}
WHERE
`meta_key` = \'show-in-blog\'
AND `post_id` = posts.`ID`
)
) /* OR */
) /* AND */
) /* WHERE */
ORDER BY `post_date` DESC;
<小时>$args = array(
// Only include IDs returned by the above query
\'post__in\' => $wpdb->get_col( $query ),
\'posts_per_page\' => 10,
);
$wp_query = new WP_Query( $args );
get_template_part(\'loop\', \'frontpage\');