Hàm lấy tag theo chuyên mục

Cập nhật lần cuối vào

Nếu bạn muốn lấy tag theo chuyên mục nào đó thì bạn cũng có thể làm được. Trong bài viết này mình sẽ hướng dẫn cho các bạn cách tạo hàm lấy post_tag theo category nói riêng, cũng như lấy tag theo chuyên mục của custom taxonomy bất kỳ.

function hocwp_get_tags_by_category( $args ) {
	global $wpdb;
	if ( ! hocwp_array_has_value( $args ) ) {
		if ( hocwp_id_number_valid( $args ) ) {
			$args = array(
				'taxonomy' => 'category',
				'term_ids' => array( $args )
			);
		} elseif ( is_a( $args, 'WP_Term' ) ) {
			$args = array(
				'taxonomy' => $args->taxonomy,
				'term_ids' => array( $args->term_id )
			);
		}
	}
	$taxonomy     = hocwp_get_value_by_key( $args, 'taxonomy', 'category' );
	$term_ids     = hocwp_get_value_by_key( $args, 'term_ids' );
	$tag_taxonomy = hocwp_get_value_by_key( $args, 'tag_taxonomy', 'post_tag' );
	if ( ! hocwp_array_has_value( $term_ids ) ) {
		return null;
	}
	$term_ids = implode( ',', $term_ids );
	$tags     = $wpdb->get_results( "
		SELECT DISTINCT terms2.term_id as tag_id, terms2.name as tag_name, null as tag_link
		FROM $wpdb->posts as p1
			LEFT JOIN $wpdb->term_relationships as r1 ON p1.ID = r1.object_ID
			LEFT JOIN $wpdb->term_taxonomy as t1 ON r1.term_taxonomy_id = t1.term_taxonomy_id
			LEFT JOIN $wpdb->terms as terms1 ON t1.term_id = terms1.term_id,
			$wpdb->posts as p2
			LEFT JOIN $wpdb->term_relationships as r2 ON p2.ID = r2.object_ID
			LEFT JOIN $wpdb->term_taxonomy as t2 ON r2.term_taxonomy_id = t2.term_taxonomy_id
			LEFT JOIN $wpdb->terms as terms2 ON t2.term_id = terms2.term_id
		WHERE
			t1.taxonomy = '$taxonomy' AND p1.post_status = 'publish' AND terms1.term_id IN (" . $term_ids . ") AND
			t2.taxonomy = '$tag_taxonomy' AND p2.post_status = 'publish'
			AND p1.ID = p2.ID
		ORDER by tag_name
	" );
	$result   = array();
	foreach ( $tags as $tag ) {
		$term = get_term_by( 'id', $tag->tag_id, $tag_taxonomy );
		if ( is_a( $term, 'WP_Term' ) ) {
			$result[] = $term;
		}
	}

	return $result;
}

Hàm bên trên sẽ giúp bạn lấy tag liên quan đến chuyên mục bất kỳ, bên trong nội dung của hàm mình có dùng một vài hàm do mình đã viết sẵn, do vậy bạn cần chỉnh sửa lại đôi chút thì mới có thể sử dụng được.

Theo dõi
Thông báo của
guest

4 Comments
Cũ nhất
Mới nhất Được bỏ phiếu nhiều nhất
Phản hồi nội tuyến
Xem tất cả bình luận
Thái Jerry
7 năm trước

yeap! hay đó, nhìn đoạn code này thì có vẻ bác là dân code chứ k phải wp

Hải Anh
7 năm trước

Bác có mở lớp dạy không, hay nhận đệ không cho em theo với 😀