Search Post Title Only

时间:2013-04-18 作者:Shawn

我正在使用标准WordPress搜索表单搜索自定义帖子类型。这是我的代码:

<form role="search" method="get" id="searchform" action="<?php echo home_url( \'/\' ); ?>">
<input type="hidden" name="post_type" value="attorney" />
<input type="text" value="" name="s" />
<input type="submit" value="Search" />
</form>
我想将此限制为仅搜索帖子标题。有没有办法做到这一点?非常感谢。

2 个回复
最合适的回答,由SO网友:Jesse 整理而成

我没有测试下面的代码,但我想它可以工作。

/**
 * Search SQL filter for matching against post title only.
 */
function __search_by_title_only( $search, &$wp_query )
{
     /*my solution */
     if($_GET[\'post_type\'] != \'attorney\' )
        return $search;
     /*my solution*/


     //please copy the rest of the code from the link below
}
add_filter( \'posts_search\', \'__search_by_title_only\', 500, 2 );

how to limit search to post titles?

SO网友:Muhammad Rezha

将此代码添加到funtions.php;

// Search by Post Title
function search_by_title_only( $search, &$wp_query )
{
    global $wpdb;
    if ( empty( $search ) )
        return $search; // skip processing - no search term in query
    $q = $wp_query->query_vars;
    $n = ! empty( $q[\'exact\'] ) ? \'\' : \'%\';
    $search = \'\';
    $searchand = \'\';
    foreach ( (array) $q[\'search_terms\'] as $term ) {
        $term = esc_sql( like_escape( $term ) );
        $search .= "{$searchand}($wpdb->posts.post_title LIKE \'{$n}{$term}{$n}\')";
        $searchand = \' AND \';
    }
    if ( ! empty( $search ) ) {
        $search = " AND ({$search}) ";
        if ( ! is_user_logged_in() )
            $search .= " AND ($wpdb->posts.post_password = \'\') ";
    }
    return $search;
}
add_filter( \'posts_search\', \'search_by_title_only\', 500, 2 );

结束

相关推荐

Query by post title

我为我的一个网站使用了自定义帖子类型。自定义帖子类型包含临时卡片数据以及一些自定义字段。我开发了一个android应用程序来管理android设备上的这些项目。在android应用程序中,我想保留搜索功能,这将帮助管理员用户搜索卡号来管理这些卡号。我可以使用wordpress查询按标题搜索。Code $args = array(\"post_type\" => \"mytype\", \"name\" => $title); $query = get_posts( $args