【问题标题】:Wordpress Search results separate main posts from Custom Post TypeWordpress 搜索结果将主要帖子与自定义帖子类型分开
【发布时间】:2017-10-02 23:41:15
【问题描述】:

我有一个名为“艺术家”的自定义帖子类型。 我当前的搜索结果将这种帖子类型与我的标准帖子放在一个分组中。 我无法在结果中区分这两种帖子类型。

而不是...

  • 博文
  • 博文
  • 艺术家帖子
  • 博文
  • 艺术家帖子

我想要……

博文:

  • 博文
  • 博文
  • 博文

艺术家发帖:

  • 艺术家帖子
  • 艺术家帖子

这可能吗?我不确定是否可以通过一个循环/查询来解决这个问题,还是使用两个查询会更快?

当前代码在这里...

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <header class="entry-header">
        <?php the_title( sprintf( '<h1 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h1>' ); ?>

        <?php if ( 'post' == get_post_type() ) : ?>
        <div class="entry-meta">
            <?php the_date(); ?>
        </div><!-- .entry-meta -->
        <?php endif; ?>
    </header><!-- .entry-header -->

    <div class="entry-summary">
        <?php the_excerpt(); ?>
    </div><!-- .entry-summary -->
</article><!-- #post-## -->

任何帮助表示赞赏。我意识到已经有一些类似的问题,但大多数对这种特殊情况没有帮助。

【问题讨论】:

    标签: php wordpress loops search


    【解决方案1】:

    只需改变 wp_query 对象的顺序

    $args = array(
        'order' => 'type'
    );
    $query = new WP_Query( $args );
    

    OP 懒得看文档所以这里我举个例子:

    $args = array('order' => 'type');
    $my_query = new WP_Query( $args );
    while ( $my_query->have_posts() ) {
     //
    }
    

    编辑: 如果您想避免使用新的 wp-query 实例并使用全局对象,这是另一种可能的解决方案:

    add_filter('posts_orderby','my_sort_custom',10,2);
    function my_sort_custom( $orderby, $query ){
        global $wpdb;
    
        if(!is_admin() && is_search()) 
            $orderby =  $wpdb->prefix."posts.post_type ASC"
    
        return  $orderby;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      相关资源
      最近更新 更多