在WP_Query中使用LIKE%some_title%实现add_filter

时间:2013-04-19 10:21:57

标签: php wordpress

我正在尝试为我的WP_Query(代码下方)添加一个过滤器来搜索post_title LIKE%some_title%

$args = array(
    'post_type' => 'product',
    'posts_per_page' => $page_size,
    'paged' => $page,
    'post_status'      => 'publish',
    'orderby'          => 'title', 
    'order'            => 'ASC',

  );

  $result = new WP_Query($args);

如何使用$ some_title添加过滤器以匹配产品标题?

1 个答案:

答案 0 :(得分:3)

你可以这样试试

$query = "
        SELECT      *
        FROM        $wpdb->posts
        WHERE       $wpdb->posts.post_title LIKE '$param2%'
        ORDER BY    $wpdb->posts.post_title
";
$wpdb->get_results($query);

替代方式和标准方式

add_filter( 'posts_where', 'wpse18703_posts_where', 10, 2 );
function wpse18703_posts_where( $where, &$wp_query )
{
    global $wpdb;
    if ( $wpse18703_title = $wp_query->get( 'wpse18703_title' ) ) {
        $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'' . esc_sql( like_escape( $wpse18703_title ) ) . '%\'';
    }
    return $where;
}

以这种方式使用

$args = array(
    'post_type' => 'product',
    'wpse18703_title' => 'your string',
    'posts_per_page' => $page_size,
    'paged' => $page,
    'post_status'      => 'publish',
    'orderby'          => 'title', 
    'order'            => 'ASC',

  );
 $result = new WP_Query($args);