add_filter函数无法按预期工作

时间:2014-06-27 11:32:35

标签: sql wordpress wp-query add-filter

我尝试使用add_filter function在WordPress中编辑wp_query。当我var_dump我的查询request时,它会按预期输出SQL。

然而,当它运行时,它返回一个不同查询的错误!有谁知道为什么查询可能会改变,并且改变太多了!

来自request var_dump的查询(正如预期的那样):

SELECT SQL_CALC_FOUND_ROWS  wp_posts.*, 
    ( 3959 * acos(
         cos( radians(52.486243) ) 
         * cos( radians( lat ) ) 
         * cos( radians( lng ) - radians(-1.890401) ) 
         + sin( radians(52.486243) ) 
         * sin( radians( lat ) ) 
         ) ) 
     AS distance , lat AS  latitude , lng AS longitude 
FROM wp_posts  
INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) 
INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
INNER JOIN wp_postmeta AS mt1 ON (wp_posts.ID = mt1.post_id) 
INNER JOIN lat_lng_post ON wp_posts.ID = lat_lng_post.post_id 
WHERE 1=1  
AND ( wp_term_relationships.term_taxonomy_id IN (2) ) 
AND wp_posts.post_type = 'event' 
AND ((wp_posts.post_status = 'publish')) 
AND ( (wp_postmeta.meta_key LIKE 'date_%_start-date' AND CAST(wp_postmeta.meta_value AS SIGNED) <= '20140704')
AND  (mt1.meta_key LIKE 'date_%_end-date' AND CAST(mt1.meta_value AS SIGNED) >= '20140627') ) 
AND lat_lng_post.lat = lat 
AND lat_lng_post.lng = lng 
AND substr(wp_postmeta.meta_key, 1, 6) = substr(mt1.meta_key, 1, 6)  
GROUP BY wp_posts.ID 
HAVING distance <= 20 
ORDER BY distance ASC 
LIMIT 0, 10

这是在错误[Unknown column 'lat' in 'field list']下面显示的查询(不是预期的):

SELECT wp_posts.*, 
    ( 3959 * acos( 
        cos( radians(52.486243) ) 
        * cos( radians( lat ) ) 
        * cos( radians( lng ) - radians(-1.890401) ) 
        + sin( radians(52.486243) ) 
        * sin( radians( lat ) ) 
     ) ) AS distance , lat AS latitude , lng AS longitude 
FROM wp_posts 
WHERE 1=1 
AND wp_posts.post_type = 'acf-field' 
AND ((wp_posts.post_status = 'publish')) 
AND wp_posts.post_name = 'field_535e6b9ffe3da' 
AND lat_lng_post.lat = lat 
AND lat_lng_post.lng = lng 
GROUP BY wp_posts.ID 
HAVING distance <= 20 
ORDER BY distance ASC 
LIMIT 0, 1

请注意

我有一个名为lat_lng_post的自定义表格,其中包含三列post_idlatlng来存储每个事件的位置数据(自定义帖子类型)。< / p>

编辑查询中使用的所有add_filter函数:

function distance_query($distance) {

    $lat = $_SESSION['search']['lat'];
    $lng = $_SESSION['search']['long'];


    $distance .= ", 
    ( 3959 * acos(
         cos( radians(".$lat.") ) 
         * cos( radians( lat ) ) 
         * cos( radians( lng ) - radians(".$lng.") ) 
         + sin( radians(".$lat.") ) 
         * sin( radians( lat ) ) 
         ) ) 
     AS distance , lat AS  latitude , lng AS longitude";
    return $distance;
}
add_filter('posts_fields', 'distance_query');



// add lat_lng_post table inner join
function lat_lng_join($join) {
    $join = str_replace('(wp_posts.ID = mt1.post_id)', '(wp_posts.ID = mt1.post_id) INNER JOIN lat_lng_post ON wp_posts.ID = lat_lng_post.post_id', $join);
    return $join;
}
add_filter('posts_join', 'lat_lng_join');


// set lat lng definition
function lat_lng_define($define) {
    $define .= ' AND lat_lng_post.lat = lat AND lat_lng_post.lng = lng';
    return $define;
}
add_filter('posts_where', 'lat_lng_define');


// HAVING distance less than user distance
function having_distance($having) {
    $radius = $_SESSION['search']['distance'];
    $having = 'wp_posts.ID HAVING distance <= '.$radius.'';
    return $having;
}
add_filter('posts_groupby', 'having_distance');

// if sorting by distance
function sort_distance($sortdistance) {
    $sortdistance = 'distance ASC';
    return $sortdistance;
}
if( $_SESSION['search']['sort-by'] == 'distance' ) :
    add_filter('posts_orderby', 'sort_distance');
endif;


function add_additional_where_condition($where) {
    $where .= " AND substr(wp_postmeta.meta_key, 1, 6) = substr(mt1.meta_key, 1, 6) ";
    return $where;
}

// fix for setting the date to search field
function date_to( $to ) {
    $to = str_replace("mt1.meta_key = 'date_%_end-date'", "mt1.meta_key LIKE 'date_%_end-date'", $to);
    return $to;
}

// fix for setting the date from search field   
function date_from( $from ) {
    $from = str_replace("meta_key = 'date_%_start-date'", "meta_key LIKE 'date_%_start-date'", $from);
    return $from;
}

// fix for ordering by date
function order_date( $like ) {
    $like = str_replace("mt2.meta_key = 'date_%_end-date'", "mt2.meta_key LIKE 'date_%_end-date'", $like);
    return $like;
}

// fix for searching by LIKE post title, requires all characters to match 
function title_filter( $where, &$wp_query ) {
    global $wpdb;
    if ( $search_term = $wp_query->get( 'title_like' ) ) {
        $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( like_escape( $search_term ) ) . '%\'';
    }
    return $where;
}

此外,这是wp_query本身将这些功能添加到:

// add query for title
    add_filter( 'posts_where', 'title_filter', 10, 2 );

// dates to and from logic
    add_filter('posts_where', 'date_from');
    add_filter('posts_where', 'date_to');
    add_filter('posts_where', 'order_date');
    add_filter('posts_where', 'add_additional_where_condition');


// get date inputs from search
    $date1 = str_replace('/', '-', $_SESSION['search']['from']);
    $when = date("Ymd", strtotime($date1));

    $date2 = str_replace('/', '-', $_SESSION['search']['to']);
    $when2 = date("Ymd", strtotime($date2));

    $year = date('Y');




// Declare the query arguments 
    if ( get_query_var('paged') ) { 
        $paged = get_query_var('paged'); 
    } else if ( get_query_var('page') ) {
        $paged = get_query_var('page'); 
    } else {
        $paged = 1; 
    }

// make keywords an array
    $keywordString = $_SESSION['search']['keyword'];
    $keywords = explode(', ', $keywordString);

    $taxQuery = array(
        'relation' => 'AND',
        array (
            'taxonomy' => 'main-cat',
            'field' => 'slug',
            'terms' => $_SESSION['search']['cat']
        )
    );

    if( $_SESSION['search']['keyword'] != '' ) {
        $taxQuery[] = array(
            'taxonomy' => 'sub-cat',
            'field' => 'name',
            'terms' => $keywords
        );
    }

    $args = array(
        // general
        'post_type' => 'event',
        'post_status' => 'publish',
        'posts_per_page' => 10,
        'paged' => $paged,
        'cache_results' => false,
        'update_post_meta_cache' => false,
        'update_post_term_cache' => false,

        'meta_key' => $_SESSION['search']['sort-key'],
        'orderby' => $_SESSION['search']['sort-by'],
        'order' => 'ASC',

        // category filter
        'tax_query' => $taxQuery,

        // date filter

        'meta_query' => array(
            'relation' => 'AND',
            array(
                'key' => 'date_%_start-date',
                'value' => $when2,
                'compare' => '<=',
                'type' => 'NUMERIC'
            ),
            array (
                'key' => 'date_%_end-date',
                'value' => $when,
                'compare' => '>=',
                'type' => 'NUMERIC'
            )

        )
    );


    $temp = $wp_query;
    $wp_query = null;
    $wp_query = new WP_Query( $args );

1 个答案:

答案 0 :(得分:4)

您似乎正在尝试为辅助查询设置posts_*过滤器,但是忘记以后删除过滤器,因此它们是影响以后运行的其他查询。

i)您可以使用remove_filter()功能删除过滤器。这是一个例子:

// Add some filter:
add_filter( 'some_filter', 'some_filter_callback', $priority );

// Run a secondary query:
$wp_query = new WP_Query( $args );

// Remove the previous filter:
remove_filter( 'some_filter', 'some_filter_callback', $priority );

过滤器优先级必须匹配。

ii)另一种方法是在remove_filter()函数中添加some_filter_callback()。例如:

add_filter( 'some_filter', 'some_filter_callback' );
$wp_query = new WP_Query( $args );

其中

some_filter_callback( $string )
{
    // Remove the current filter:
    remove_filter( current_filter(), __FUNCTION__ );

    // Some modifications to the input:
    // ...

    // Output:
    return $string;
}

这将确保您的过滤器只运行一次。

iii)如果您尝试修改主查询,可以使用以下命令限制过滤器:

if( ! is_admin() && is_main_query() )
{
     // ...
}

if( ! is_admin() && $query->is_main_query() )
{
     // ...
}

如果您使用pre_get_posts挂钩,其中$query是输入参数。

iv)另一种选择是创建一个扩展WP_Query的新类,并包含您想要的所有过滤器:

class My_Search_Query extends WP_Query
{
   // ...
}

你在哪里使用

$query = new My_Search_Query( $args );

运行查询。