搜索帖子标题的查询

时间:2015-01-08 06:06:47

标签: php wordpress

我想通过post_title搜索WordPress自定义帖子类型,我正在使用

$spot_args = array(
            "post_type" => "spot",
            "post_status" => "publish",
            "posts_per_page" => -1,
            "meta_query" => $meta_build //array that contain meta condition
        );  
$wp_query = new WP_Query($spot_args);

现在如何为post_title添加过滤器, 不影响使用

add_filter('posts_where', 'post_title_condition');
function post_title_condition($where) {
    global $wpdb;
    where .= ' OR ' . $wpdb->posts . 'post_title LIKE %' . $title. '% ';
    $where;
}

所以任何方式?

3 个答案:

答案 0 :(得分:3)

试试这个

<?php
$yourPostTitle='xyz';
$yourPostTitle=strtoupper($yourPostTitle);
$ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE UCASE(post_title) LIKE '%$yourPostTitle%' AND post_type='spot' AND post_status='publish'");
if ($ids) {
  $args=array(
    'post__in' => $ids,
    'posts_per_page' => -1,
    'caller_get_posts'=> 1
  );
  $my_query = null;
  $my_query = new WP_Query($args);
  if( $my_query->have_posts() ) {
    echo 'List of Posts';
    while ($my_query->have_posts()) : $my_query->the_post(); ?>
      <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
      <?php
    endwhile;
  }
wp_reset_query();  // Restore global post data stomped by the_post().
}
?>

快乐编码:)

答案 1 :(得分:0)

使用像这样的mysql查询:

$query = 'SELECT guid, post_content, post_title, post_parent, post_type FROM wp_posts WHERE (post_title LIKE '%".$title."%') AND post_type="spot"';

答案 2 :(得分:0)

试试这个

<?php
if(isset($_REQUEST['postname'])){
    $postname = $_REQUEST['postname'];
    $paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
    add_filter( 'posts_where', 'wpse18703_posts_where', 10, 2 );
    function wpse18703_posts_where( $where, &$wp_query ){
        global $wpdb;
        if ( $wpse18703_title = $wp_query->get( 'title' ) ) {
            $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( $wpdb->esc_like( $wpse18703_title ) ) . '%\'';
        }
        return $where;
    }

    $args = array(
        'post_type' => 'spot',
        'posts_per_page' => 10,
        'paged' => $paged,
        'title' => $postname,
        'post_status' => 'publish',
        'orderby'     => 'title', 
        'order'       => 'ASC'
    );

    $loop = new WP_Query($args);
}
?>