WordPress管理面板搜索带有自定义帖子元值和标题的帖子

时间:2014-01-31 作者:Vin_fugen

试图通过包含“按自定义帖子类型搜索”字段来修改默认管理员搜索,

下面是我的代码,

function custom_search_query( $query ) {
    $custom_fields = array(
        // put all the meta fields you want to search for here
        "rg_1job_designation",
        "rg_2job_designation"
    );
    $searchterm = $query->query_vars[\'s\'];
    // we have to remove the "s" parameter from the query, because it will prevent the posts from being found
    $query->query_vars[\'s\'] = "";
    if ($searchterm != "") {
        $meta_query = array(\'relation\' => \'OR\');
        foreach($custom_fields as $cf) {
            array_push($meta_query, array(
                \'key\' => $cf,
                \'value\' => $searchterm,
                \'compare\' => \'LIKE\'
            ));
        }
        $query->set("meta_query", $meta_query);
    };
}
add_filter( "pre_get_posts", "custom_search_query");
但它不起作用。

我有一个帖子title -> John &;Designation -> Designer 按搜索Designer 可以获得1个结果,但在搜索时John 结果为空(这还应获取一个结果)。现在,对标题的默认搜索丢失了,我也想使用它。

有人知道我的代码出了什么问题吗?

1 个回复
SO网友:Seyed Abbas Seyedi

使用此代码,您可以search 在WordPress管理面板的帖子列表中custom post meta 值以及title 和其他默认字段。

请在函数中添加以下代码。php文件:

if (!function_exists(\'extend_admin_search\')) {
    add_action(\'admin_init\', \'extend_admin_search\');

    /**
     * hook the posts search if we\'re on the admin page for our type
     */
    function extend_admin_search() {
        global $typenow;

        if ($typenow === \'your_custom_post_type\') {
            add_filter(\'posts_search\', \'posts_search_custom_post_type\', 10, 2);
        }
    }

    /**
     * add query condition for custom meta
     * @param string $search the search string so far
     * @param WP_Query $query
     * @return string
     */
    function posts_search_custom_post_type($search, $query) {
        global $wpdb;

        if ($query->is_main_query() && !empty($query->query[\'s\'])) {
            $sql    = "
            or exists (
                select * from {$wpdb->postmeta} where post_id={$wpdb->posts}.ID
                and meta_key in (\'rg_1job_designation\',\'rg_2job_designation\')
                and meta_value like %s
            )
        ";
            $like   = \'%\' . $wpdb->esc_like($query->query[\'s\']) . \'%\';
            $search = preg_replace("#\\({$wpdb->posts}.post_title LIKE [^)]+\\)\\K#",
                $wpdb->prepare($sql, $like), $search);
        }

        return $search;
    }
}

结束

相关推荐

Display Search Result Count

到目前为止,我一直在使用下面的代码来获取搜索结果的数量,并显示该计数。<?php /* Search Count */ $allsearch =& new WP_Query(\"s=$s&showposts=-1\"); $count = $allsearch->post_count; echo $count . \' \'; wp_reset_query(); ?> 但这似乎不是有效的代码。显示以下错误:不推荐:不推荐通过引用分配new的返回值请任何人建议我获