针对大量的post meta优化WP Meta查询?

时间:2018-05-17 11:58:07

标签: wordpress metadata

我有一个大型WP站点,大约有2k帖子和150k postmeta。当浏览到大类时,由于正在寻找特色帖子的WP查询,存档加载速度非常慢,以便首先显示它们。 我知道最终的目标是优化postmeta表,但是现在我想知道是否有任何可能的方法来优化下面的元查询(一个在底部)。

我做了一些调试(参见//comments),发现'compare' => '!='导致查询变得非常慢。我还发现'''<'正在加快查询速度,结果相同,但我不确定这是否是一种正确的方法。如果有办法加快此查询,请告诉我。感谢

function appthemes_addon_on_top_query( $wp_query ){

    $addon_type = $wp_query->get( 'addon_on_top' );

    if( ! $addon_type || ! appthemes_addon_exists( $addon_type ) ) {
        return;
    }

    $addon_info = appthemes_get_addon_info( $addon_type );
    $flag_key   = $addon_info['flag_key']; //custom field for featured posts
    $meta_query = (array) $wp_query->get( 'meta_value', 1 );
    $meta_query = array_filter( $meta_query );
    $meta_query[] = array(
        'relation' => 'OR',
        array(
            'key'     => $flag_key,
            'compare' => 'NOT EXISTS',
        ),
        array(
            'relation' => 'OR',
            //Deleting the array below makes the query quick, but i need it to show featured posts first
            array(
                'key'   => $flag_key,
                'value' => 1,
            ),
            //Deleting the array below makes the query quick, but i need it to properly sorting the posts by date (see below: $wp_query->set( 'orderby')
            array(
                'key'     => $flag_key,
                'value'   => 1,
                'compare' => '!=', //It is about this comparison. '' or '<' makes the query quick, but i am not sure if that is a proper replacement. Also not sure why '!=' makes it this slow.
            ),
        ),
    );

    $wp_query->set( 'meta_query', $meta_query );
    $wp_query->set( 'orderby', array( 'meta_value' => 'DESC', 'date' => 'DESC' ) );
}

1 个答案:

答案 0 :(得分:0)

好的,我发现'compare' => '!='减慢速度,但'compare' => '<>'却没有。我猜两者都是一样的,所以我想这个问题已经解决了。