Skip to main content

[Thủ Thuật WordPress] Custom Taxonomy trong WordPress

Taxonomy WordPress là gì?

Taxonomy WordPress là một cách thức nhóm nội dung lại với nhau.

Taxonomy WordPress giúp bạn có thể cấu trúc/ phân chia/ nhóm gộp một lượng lớn nội dung theotheo từng nhóm giúp bạn dễ quản lý hơn.

Trong WordPress mặc định phổ biến có hai loại taxonomy là danh mục (categories) và thẻ (tags). Nhưng theo WordPress mặc định cung cấp bốn built-in taxonomies : 

  1. Categories (hierarchal) : Taxonomy Category giúp bạn nhóm các bài viết theo thể loại của nó.
  2. Tags (multifaceted): Tags cũng đơn giản giống như categories – nó nhóm các bài post lại với nhau. Tuy nhiên, nó không có cấu trúc dạng cây như categories.
  3. Links (multifaceted): Taxonomy này giúp bạn phân loại các link. Nếu bạn link tới các nguồn cho bài viết của bạn, bạn sẽ cần dùng taxonomy link .
  4. Navigation menu (hierarchal)

Custom Taxonomies WordPress là gì?

Custom Taxonomies WordPress là những taxonomies nằm ngoài 4 taxonomies mặc định của WordPress mà bạn thêm vào thủ công, nhằm giúp bạn phân loại post của bạn tốt hơn.

Ví dụ, nếu như bạn tạo một website thể dục. Thay vì chỉ có một categories chung chung, bạn có thể tạo thêm một taxonomies mới có tên “Cardio” và “Floor Exercises”.

Mỗi taxonomy có thể được chỉnh sửa thêm nữa để chèn thêm categories phụ như “Jogging”, “Intermittent running”, và “Crunches”.

Tạo Custom Taxonomies WordPress - Hierarchical taxonomy (category)

Dưới đây là snippet code vào trong file functions.php tạo một category "Location" demo 

function add_custom_taxonomies()
{
    // Add new "Locations" taxonomy to Posts
    register_taxonomy('location', 'post', array(
        // Hierarchical taxonomy (like categories)
        'hierarchical' => true,
        // This array of options controls the labels displayed in the WordPress Admin UI
        'labels' => array(
            'name' => _x('Locations', 'taxonomy general name'),
            'singular_name' => _x('Location', 'taxonomy singular name'),
            'search_items' =>  __('Search Locations'),
            'all_items' => __('All Locations'),
            'parent_item' => __('Parent Location'),
            'parent_item_colon' => __('Parent Location:'),
            'edit_item' => __('Edit Location'),
            'update_item' => __('Update Location'),
            'add_new_item' => __('Add New Location'),
            'new_item_name' => __('New Location Name'),
            'menu_name' => __('Locations'),
        ),
        // Control the slugs used for this taxonomy
        'rewrite' => array(
            'slug' => 'locations', // This controls the base slug that will display before each term
            'with_front' => false, // Don't display the category base before "/locations/"
            'hierarchical' => true // This will allow URL's like "/locations/boston/cambridge/"
        ),
    ));
}
add_action('init', 'add_custom_taxonomies', 0);

Sau đó vào trong edit post để thấy category mới xuất hiện.

Image
Tạo Custom Taxonomies WordPress - category Location

Tạo một Taxonomy Template cho WordPress

Sau khi bạn tạo một custom Taxonomy WordPress, để hiển thị nội dung bạn có thể sử dụng template:

  • taxonomy-{taxonomy}-{slug}.php: ví dụ ở đây là taxonomy-location-boston.php
  • taxonomy-{taxonomy}.php: tương ứng là taxonomy-location.php
  • taxonomy.php: dùng chung cho tất cả các taxonomies
  • archive.php: Nếu không tìm thấy template cụ thể về phân loại, thì sẽ sử dụng archive.php.

Dưới đây là ví dụ hiển thị taxonomy-location.php:

<?php
/**
 * Locations taxonomy archive
 */
get_header();
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
?>
<div class="wrapper">
  <div class="primary-content">
    <h1 class="archive-title"><?php echo apply_filters( 'the_title', $term->name ); ?> News</h1>

    <?php if ( !empty( $term->description ) ): ?>
    <div class="archive-description">
      <?php echo esc_html($term->description); ?>
    </div>
    <?php endif; ?>

    <?php if ( have_posts() ): while ( have_posts() ): the_post(); ?>

    <div id="post-<?php the_ID(); ?>" <?php post_class('post clearfix'); ?>>
      <h2 class="post-title"><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
      <div class="content clearfix">
        <div class="post-info">
          <p><?php the_time(get_option('date_format')); ?> by <?php the_author_posts_link(); ?></p>
        </div><!--// end .post-info -->
        <div class="entry">
          <?php the_content( __('Full story…') ); ?>
        </div>
      </div>
    </div><!--// end #post-XX -->

    <?php endwhile; ?>

    <div class="navigation clearfix">
      <div class="alignleft"><?php next_posts_link('« Previous Entries') ?></div>
      <div class="alignright"><?php previous_posts_link('Next Entries »') ?></div>
    </div>

    <?php else: ?>

    <h2 class="post-title">No News in <?php echo apply_filters( 'the_title', $term->name ); ?></h2>
    <div class="content clearfix">
      <div class="entry">
        <p>It seems there isn't anything happening in <strong><?php echo apply_filters( 'the_title', $term->name ); ?></strong> right now. Check back later, something is bound to happen soon.</p>
      </div>
    </div>

    <?php endif; ?>
  </div><!--// end .primary-content -->

  <div class="secondary-content">
    <?php get_sidebar(); ?>
  </div><!--// end .secondary-content -->

<?php get_footer(); ?>

Tạo một Taxonomy Tag Cloud

Để hiển thị Taxonomy cloud tag 'location' bằng :

// Locations tag cloud
<?php
$locations_cloud = wp_tag_cloud( array(
  'taxonomy' => 'location',
  'echo' => 0
) );

// Make sure there are terms with articles
if ( $locations_cloud ): ?>
<h2>News by Location</h2>
<div class="locations-cloud">
  <?php echo $locations_cloud; ?>
</div>
<?php endif; ?>

WP_QUERY và TAX_QUERY

Dưới đây là cách lấy bài post mới nhất tại Boston

<?php
/**
 * Display a list of the most recent news in Boston
 *
 * @class WP_Query http://codex.wordpress.org/Class_Reference/WP_Query
 */
$locations_query = new WP_Query( array(
  'post_type' => 'post',
  'posts_per_page' => 10,
  'tax_query' => array(
    array(
      'taxonomy' => 'location',
      'field' => 'slug',
      'terms' => 'boston'
    )
  )
) );
// Display the custom loop
if ( $locations_query->have_posts() ): ?>
<h2>Latest News in Boston</h2>
<ul class="postlist">
  <?php while ( $locations_query->have_posts() ) : $locations_query->the_post(); ?>
  <li><span class="date"><?php the_time(get_option('date_format')); ?></span> – <a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></li>
  <?php endwhile; wp_reset_postdata(); ?>
</ul><!--// end .postlist -->
<?php endif; ?>