search query for post title

2019-09-21 06:46发布

问题:

I want to search WordPress custom post type by post_title and i am using

$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);

Now how to add filter for post_title, Not effect of using

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

so any way ??

回答1:

Try this

<?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().
}
?>

Happy Coding :)



回答2:

use mysql query like this:

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


回答3:

Try this

<?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);
}
?>


标签: php wordpress