【问题标题】:WordPress get_posts by title likeWordPress get_posts 按标题喜欢
【发布时间】:2014-09-26 01:22:28
【问题描述】:

我正在尝试为 WordPress 创建一个小型搜索功能。 AJAX 调用应该获取标题为%quote% 的所有帖子。

是否有可能在 get_posts() 函数中实现这一点?

不要误会我的意思。 ajax 工作正常。我的functions.php中有ajax函数,我收到了帖子。这只是我找不到解决方案的“标题喜欢”部分。

【问题讨论】:

    标签: wordpress get title posts


    【解决方案1】:

    您也可以进行自定义搜索查询。

    $search_query = "SELECT ID FROM {$wpdb->prefix}posts
                             WHERE post_type = 'post' 
                             AND post_title LIKE %s";
        
    $like = '%' . $quote . '%';
    $results = $wpdb->get_results($wpdb->prepare($search_query, $like), ARRAY_A);
    
    $quote_ids = array_column($results, 'ID');
    
    $quotes = get_posts(array('post_type'=>'post', 'orderby'=>'title', 'order'=>'ASC', 'post__in' => $quote_ids));
    

    【讨论】:

    • 有点晚了,但这为我节省了几个小时的研究时间。
    【解决方案2】:

    不,但您可以创建自定义循环。

    Check this.

    编辑:

    $args = array('s' => 'keyword');
    
    $the_query = new WP_Query( $args );
    
    // The Loop
    if ( $the_query->have_posts() ) {
        
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            //whatever you want to do with each post
        }
    } else {
         // no posts found
    }   
    

    【讨论】:

    • 请在您的答案中添加相关信息,因为如果链接断开或更改,则没有任何用处。
    • 如果不执行while,我可以从if 语句中的帖子中获取一个字段吗?
    • @Si8。 'if' 检查查询是否有帖子。你想用它来获得一个帖子吗?
    • 我最终使用了这个:$posts = $wp_query->posts; 而不是while,这导致我的页面的其余部分无法生成。感谢您的答复。我 +1 是因为你的帖子帮助我找到了正确的方向。
    【解决方案3】:

    或者您可以像这样使用过滤器posts_where:

    $options = array(
        'posts_per_page' => -1,
        'suppress_filters' => false, // important!
        'post_type' => 'post',
        'post_status' => 'publish',
    );
    $keyword = 'quote';
    
    add_filter( 'posts_where', 'my_filter_post_where' );
    $posts = get_posts( $options );
    remove_filter( 'posts_where', 'my_filter_post_where' );
    
    function my_filter_post_where( $where) {
        global $wpdb;
        global $keyword;
    
        $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( like_escape( $keyword ) ) . '%\'';
    
        return $where;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      相关资源
      最近更新 更多