TODO: To change the header's content go to Dr.Explain menu Options : Project Settings : HTML (CHM) Export : Setup HTML Template and Layout
×
Menu
Index

Xắp xếp custom posts theo taxonomy

 
Nhóm posts theo taxonomy, các posts có cùng taxonomy liệt kê cùng với nhau.
Cách 1: Chúng ta sẽ sử dụng 2 vòng lặp, đầu tiên sẽ lấy category terms và sau đó lấy các posts thuộc mỗi category đó.
<!-- Begin custom tax loop -->
  <?php
  //Retrieve custom taxonomy terms using get_terms and the custom post type.
    $categories = get_terms('tn_cstm_work_taxonomy','orderby=name');
   //Iterate through each term
    foreach ( $categories as $category ) :
    ?>
      <div class="row">
       //Use $category->slug to retrieve the slug
        <section id="<?php echo $category->slug; ?>" class="large-12 columns" data-magellan-destination='<?php echo $category->slug; ?>'>
           <h3><?php echo $category->name; ?></h3>
 
           <ul class="large-block-grid-4 small-block-grid-2">
            <?php
           //Setup the query to retrieve the posts that exist under each term
            $posts = get_posts(array(
              'post_type' => 'tn_cstm_portfolio',
              'orderby' => 'menu_order',
              'order' =>  'ASC',
              'taxonomy' => $category->taxonomy,
              'term'  => $category->slug,
              'nopaging' => true,
              ));
            // Here's the second, nested foreach loop that cycles through the posts associated with this category
            foreach($posts as $post) :
              setup_postdata($post); ////set up post data for use in the loop (enables the_title(), etc without specifying a post ID--as referenced in the stackoverflow link above)
            ?>
 
              <li>
                  <?php
//retrieves the post thumbnail for each post
                         $thumb = get_post_thumbnail_id();
                          $img_url = wp_get_attachment_url( $thumb,'medium' ); //get full URL to image (use "large" or "medium" if the images too big)
                          $image = aq_resize( $img_url, 300, 270, true ); //resize & crop the image using aqua resizer https://github.com/sy4mil/Aqua-Resizer
                  ?>
    <figure class="work-thumb">
        <a class="th" href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>">
            <?php if($image) : ?>
                <img src="<?php echo $image ?>" alt="<?php the_title(); ?> thumb"/>
            <?php else : ?>
                <img class="" src="<?php bloginfo('stylesheet_directory'); ?>/img/small-placeholder.png" alt="placeholder image">
 
            <?php endif; ?>
        </a>
        <figcaption><h4><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h4></figcaption>
    </figure>
 
<?php }
                    ?>
              </li>
 
            <?php endforeach; ?>
 
          </ul>
        </section>
      </div><!-- .row -->   
 
  <?php endforeach; ?>//Easy Peasy
 
Cách này đơn giản và dễ làm tuy nhiên có một cách ưu việt hơn bạn không sử dụng hàm truy xuất dữ liệu của wordpress, chúng ta sẽ tùy biến lệnh SQL để lọc kết quả theo ý muốn, xem cách 2.
 
Cách 2: Sử dụng filter posts_clauses để sửa chuỗi SQL, cho các hàm lấy nội dung của wordpress.
add_filter( 'posts_clauses', 'mc_people_order_position', 10, 2 );
function mc_people_order_position( $clauses, $wp_query ) {
    global $wpdb;
    if( isset( $wp_query->query['orderby'] ) && 'hoang' == $wp_query->query['orderby'] ) {
          $clauses['join'] .= " INNER JOIN (SELECT {$wpdb->terms}.term_id, {$wpdb->terms}.slug, {$wpdb->term_relationships}.object_id
                    FROM {$wpdb->term_taxonomy}, {$wpdb->terms}, {$wpdb->term_relationships}
                    WHERE {$wpdb->term_taxonomy}.taxonomy = 'danh-muc'
                    AND {$wpdb->term_taxonomy}.term_id = {$wpdb->terms}.term_id
                    AND {$wpdb->term_taxonomy}.term_taxonomy_id = {$wpdb->term_relationships}.term_taxonomy_id
                    GROUP BY {$wpdb->term_relationships}.object_id
                    ) as person_position_relationship ON person_position_relationship.object_id = {$wpdb->posts}.ID";
          $clauses['groupby'] = "person_position_relationship.object_id";
          $clauses['orderby'] = " FIELD(person_position_relationship.slug, 'honda-crv', 'honda-city', 'honda-civic', 'honda-accord') ";
          $clauses['orderby'] .= ( 'ASC' == strtoupper( $wp_query->get( 'order' ) ) ) ? 'DESC' : 'ASC';
          $clauses['orderby'] .= ", person_position_relationship.slug ";
          $clauses['orderby'] .= ( 'ASC' == strtoupper( $wp_query->get( 'order' ) ) ) ? 'ASC' : 'DESC';
     }
     return $clauses;
}
 
Giải thích:
new WP_Query(array(
       'orderby' => 'hoangweb',
       'order_terms' => array('honda-crv', 'honda-city', 'honda-civic', 'honda-accord')
));
 
Sử dụng: để đoạn code xắp xếp trên hoạt động, bạn thiết lập giá trị tham số 'orderby' = 'hoang' cho WP_Query.
new WP_Query(array('orderby'=>'hoang',...));
 
Kết quả:
 
- Xắp xếp thêm một meta field:
Ví dụ xắp xếp posts nhóm theo taxonomy đồng thời xắp xếp bởi 1 meta fields có kiểu số. Đoạn code dưới đây tôi muốn xắp sản phẩm theo giá giảm dần:
new WP_Query(array(
    'orderby'=>'hoang',
    'meta_key'=>'price'
    'order' => 'DESC'
));
 
Sửa filter 'posts_clauses', bổ xung vào lệnh SQL như sau:
add_filter( 'posts_clauses', 'mc_people_order_position', 10, 2 );
function mc_people_order_position( $clauses, $wp_query ) {
    global $wpdb;
    if( isset( $wp_query->query['orderby'] ) && 'hoang' == $wp_query->query['orderby'] )   {
      /*.................same above.................*/
         //additional, refer to meta field 'price'
         $clauses['orderby'] .= ", wp_postmeta.meta_value+0 ASC";
     }
};
 
 
Made with help of Dr.Explain

Unregistered version