Created
June 29, 2017 15:09
-
-
Save igmoweb/42f69cf3c44bcbf3d2e944bf38fc8260 to your computer and use it in GitHub Desktop.
Check if a post is under knowledge category
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function yell_is_knowledge_post( $post_id ) { | |
$categories = get_the_category( $post_id ); | |
if ( in_array( 'knowledge', wp_list_pluck( $categories, 'slug' ), true ) ) { | |
return true; | |
} | |
$knowledge_cat = get_term_by( 'slug', 'knowledge', 'category' ); | |
if ( ! is_a( $knowledge_cat, 'WP_Term' ) ) { | |
// Knpwledge category does not even exist | |
return false; | |
} | |
$parent_categories_ids = array_map( 'absint', wp_list_pluck( $categories, 'parent' ) ); | |
if ( in_array( $knowledge_cat->term_id, $parent_categories_ids, true ) ) { | |
// Current category is child of Knowledge term | |
return true; | |
} | |
// Search children terms. This is the slowest method but it won't get here often | |
$categories_ids = wp_list_pluck( $categories, 'term_id' ); | |
if ( is_a( $knowledge_cat, 'WP_Term' ) ) { | |
$children_ids = get_term_children( $knowledge_cat->term_id, 'category' ); | |
if ( array_intersect( $categories_ids, $children_ids ) ) { | |
// One of the Knowledge children categories is assigned to this post | |
return true; | |
} | |
} | |
return false; | |
} | |
function test_something() { | |
$post_id = $this->factory()->post->create(); | |
$knowledge_term = $this->factory()->term->create( array( 'slug' => 'knowledge', 'taxonomy' => 'category' ) ); | |
$different_term = $this->factory()->term->create( array( 'slug' => 'different', 'taxonomy' => 'category' ) ); | |
$child_knowledge_term = $this->factory()->term->create( array( 'slug' => 'child-knowledge', 'parent' => $knowledge_term, 'taxonomy' => 'category' ) ); | |
$grandchild_knowledge_term = $this->factory()->term->create( array( 'slug' => 'child-knowledge', 'parent' => $child_knowledge_term, 'taxonomy' => 'category' ) ); | |
$this->assertFalse( yell_is_knowledge_post( $post_id ) ); | |
$this->wp_set_object_terms( $post_id, $knowledge_term, 'category' ); | |
$this->assertTrue( yell_is_knowledge_post( $post_id ) ); | |
$this->wp_set_object_terms( $post_id, $child_knowledge_term, 'category' ); | |
$this->assertTrue( yell_is_knowledge_post( $post_id ) ); | |
$this->wp_set_object_terms( $post_id, $different_term, 'category' ); | |
$this->assertFalse( yell_is_knowledge_post( $post_id ) ); | |
$this->wp_set_object_terms( $post_id, $grandchild_knowledge_term, 'category' ); | |
$this->assertTrue( yell_is_knowledge_post( $post_id ) ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment