我只想展示不为分类标准“产品品牌”设置“品牌slu”一词的帖子。
我当前的查询不适用过滤器:
SELECT DISTINCT * FROM $wpdb->posts AS p
LEFT JOIN $wpdb->postmeta AS meta ON p.ID = meta.post_id
LEFT JOIN $wpdb->term_relationships AS rel ON rel.object_id = p.ID
LEFT JOIN $wpdb->term_taxonomy AS tax ON tax.term_taxonomy_id = rel.term_taxonomy_id
LEFT JOIN $wpdb->terms AS term ON tax.term_id = term.term_id
WHERE 1=1
AND p.post_type = 'product'
AND p.post_status = 'publish'
AND p.post_title LIKE '%$trimmed%' OR (meta.meta_key = 'product_model' AND meta.meta_value LIKE '%$trimmed%')
AND (tax.taxonomy = 'product-brand' AND term.slug NOT IN ('$protected'))
分类法或slug条件似乎都不适用于上述查询。
感谢任何帮助!
答案 0 :(得分:7)
您似乎没有使用$wpdb->prepare()
,因此您冒着SQL注入的风险。
我也认为您在相关的OR部分周围缺少括号,因此您不会最终显示草稿。
我们应该能够使用WP_Query
类,而不是编写硬编码的SQL查询,并通过钩子/过滤器进行一些修改。
这是一个例子(PHP 5.4 +):
$args = [
'_meta_or_like_title' => $trimmed, // Our new custom argument!
'post_type' => 'product',
'post_status' => 'publish',
'meta_query' => [
[
'key' => 'product_model',
'value' => $trimmed, // Your meta value
'compare' => 'LIKE'
]
],
'tax_query' => [
[
'taxonomy' => 'product-brand',
'field' => 'slug',
'terms' => $protected, // Your terms array
'operator' => 'NOT IN'
]
]
];
我为另一个question here编写的稍加修改的插件支持自定义_meta_or_like_title
参数。
<?php
/**
* Plugin Name: Meta OR LIKE Title query in WP_Query
* Description: Activated through the '_meta_or_like_title' argument of WP_Query
* Plugin URI: http://stackoverflow.com/a/31241416/2078474
* Plugin Author: Birgir Erlendsson (birgire)
* Version: 0.0.1
*/
add_action( 'pre_get_posts', function( $q )
{
if( $title = $q->get( '_meta_or_like_title' ) )
{
add_filter( 'get_meta_sql', function( $sql ) use ( $title )
{
global $wpdb;
// Only run once:
static $nr = 0;
if( 0 != $nr++ ) return $sql;
// Modify WHERE part:
$sql['where'] = sprintf(
" AND ( %s OR %s ) ",
$wpdb->prepare(
"{$wpdb->posts}.post_title LIKE '%%%s%%'",
$wpdb->esc_like( $title )
),
mb_substr( $sql['where'], 5, mb_strlen( $sql['where'] ) )
);
return $sql;
});
}
}, PHP_INT_MAX );