Một bài viết có thể thuộc nhiều danh mục, trong đó sẽ có một danh mục chính (mặc định). Trường hợp bạn muốn lấy tên hoặc ID danh mục đó ra để xử lý ta dùng hàm như sau
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
/** codfe.com hàm lấy danh mục mặc định của pos **/ function get_primary_category($category){ $useCatLink = true; // If post has a category assigned. if ($category){ $category_display = ''; $category_link = ''; if ( class_exists('WPSEO_Primary_Term') ) { // Show the post's 'Primary' category, if this Yoast feature is available, & one is set $wpseo_primary_term = new WPSEO_Primary_Term( 'category', get_the_id() ); $wpseo_primary_term = $wpseo_primary_term->get_primary_term(); $term = get_term( $wpseo_primary_term ); if (is_wp_error($term)) { // Default to first category (not Yoast) if an error is returned $category_display = $category[0]->name; $category_link = get_category_link( $category[0]->term_id ); } else { // Yoast Primary category $category_display = $term->name; $category_link = get_category_link( $term->term_id ); } } else { // Default, display the first category in WP's list of assigned categories $category_display = $category[0]->name; $category_link = get_category_link( $category[0]->term_id ); } // Display category if ( !empty($category_display) ){ if ( $useCatLink == true && !empty($category_link) ){ return ''.htmlspecialchars($category_display).''; } else { return ''.htmlspecialchars($category_display).''; } } } } |
Dùng đoạn code như sau để hiện tên danh mục cần tìm:
|
1 2 |
$category = get_the_category(); echo get_primary_category($category); |
Bài viết mới:
- Ẩn các sản phẩm không muốn hiển thị trong trang danh mục woocommerce
- Cách tạo mã giảm giá (Coupon) trong website dùng Woocommerce
- Cách tạo danh mục (table of content) cho mô tả danh mục bài viết và sản phẩm
- Hướng dẫn các bạn khôi phục các file bị mất hoặc bị xóa bằng công cụ của Windows 10
- Hàm tạo breadcrumb cho wordpress



