0

我正在尝试向我的 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 匹配?

4

1 回答 1

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);
于 2013-04-19T10:27:35.077 回答