php – 如何排除结果从定制WordPress MySQL查询按分类术语

前端之家收集整理的这篇文章主要介绍了php – 如何排除结果从定制WordPress MySQL查询按分类术语前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我只想展示没有“分类”产品品牌“品牌”的帖子.

我当前的查询不适用于过滤器:

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'))

在上述查询中,分类或条件条件似乎都不起作用.

任何帮助是赞赏!

笔记:

看起来你没有使用$wpdb-> prepare(),所以你冒着sql注入的风险.

我也认为你在相关OR部分周围缺少括号,所以你不会最终显示草稿.

替代方案:

而不是编写一个硬编码的SQL查询,我们应该能够使用WP_Query类,并通过钩子/过滤器进行一些修改.

这是一个例子(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'
        ]
    ]
];

其中自定义_Meta_or_like_title参数由稍微修改插件支持,我为另一个question here写.

插入:

<?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:    https://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 );
原文链接:https://www.f2er.com/php/140119.html

猜你在找的PHP相关文章