首页 文章

按自定义分类ID列出自定义帖子类型,并按帖子ID上的数组过滤

提问于
浏览
0

嗨,我需要按类别ID获取帖子类型的结果,并使用like运算符发布 Headers .

例如

Category name : Sports  
Post name : Basketball , hockey , volley ball

从下面的查询我得到帖子名称及其ID,我将它们传递给get post查询,但查询返回该类别内的所有帖子

假设我在该类别中搜索排球我获得了所有结果我只需要输出中的排球 .

请参阅下面的我的代码

$ mypostids_title = $ wpdb-> get_col(“从$ wpdb->中选择ID,其中post_title喜欢'%$ title%'”);

$args_sby= array(
    'post_type'      => 'campaign',
    'post_status'    => 'publish',  
    'posts_per_page' => -1,    
    'post__in' => $mypostids_title, 
        'tax_query' => array(
            array(
           'taxonomy' => 'campaign_category',
           'field'    => 'term_id',                      
            'terms'    => $_GET['c'],
            'operator' => 'AND',                
            )
       ),

    );
$posts = get_posts($args_sby);

我从上面的选择查询得到post id的数组,我在get post查询参数中传递它们,我只得到分类法的结果,但我需要通过分类法和post id获得结果,请让我知道如何解决这个 . 提前致谢 .

3 回答

  • 1
    $custom_terms = get_terms('custom_taxonomy');
    
    foreach($custom_terms as $custom_term) {
        wp_reset_query();
        $args = array('post_type' => 'custom_post_type',
            'tax_query' => array(
                array(
                    'taxonomy' => 'custom_taxonomy',
                    'field' => 'slug',
                    'terms' => $custom_term->slug,
                ),
            ),
         );
    
         $loop = new WP_Query($args);
         if($loop->have_posts()) {
            echo '<h2>'.$custom_term->name.'</h2>';
    
            while($loop->have_posts()) : $loop->the_post();
                echo '<a href="'.get_permalink().'">'.get_the_title().'</a><br>';
            endwhile;
         }
    

    你可以尝试这个代码

  • 1

    尝试下面的代码,它可能会有所帮助 . 您可以直接在query_posts中传递搜索关键字和类别 .

    $args_sby= array(
        'post_type'      => 'campaign',
        'post_status'    => 'publish',  
        'posts_per_page' => -1,    
        's' => $keywords, 
        'taxonomy' => 'campaign_category',
        'term' => 'yourterm' 
        );
    $posts = query_posts($args_sby);
    

    查找参数相关帮助here

  • 1

    试试这个 . 它可能对你有所帮助 .

    $args_sby= array(
        'post_type'      => 'campaign',
        'post_status'    => 'publish',  
        'posts_per_page' => -1,
        'post_title'     => $title,
        'tax_query' => array(
            array(
                'taxonomy' => 'campaign_category',
                'field'    => 'term_slug',
                'terms'    => $_GET['c'],
                'operator' => 'AND',
            )
       ),
    );
    $posts = get_posts($args_sby);
    

    在此之后,请将以下代码放在主题的function.php文件中 .

    //Filter for post title.
    function title_filter( $where, &$wp_query ){
        global $wpdb;
        if ( $search_term = $wp_query->get( 'post_title' ) ) {
            $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . $wpdb->esc_like( $search_term) . '%\'';
        }    
        return $where;
    }
    
    add_filter( 'posts_where', 'title_filter', 10, 2 );
    

相关问题