Created
November 9, 2023 11:45
-
-
Save LaxusCroco/e4e37774958e3f16f05267936ccc6f82 to your computer and use it in GitHub Desktop.
A macro which retrieves the top-level parent of the term attached to the current post.
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 | |
add_action( 'jet-engine/register-macros', function(){ | |
class Get_Ancestor extends \Jet_Engine_Base_Macros { | |
public function macros_tag() { | |
return 'get_ancestor'; | |
} | |
public function macros_name() { | |
return esc_html__( 'Get Ancestor', 'jet-engine' ); | |
} | |
public function macros_args() { | |
return array(); | |
} | |
public function macros_callback( $args = array() ) { | |
$categories = get_the_terms(get_the_ID(), 'category'); | |
// Check if the post has terms assigned | |
if ($categories && !is_wp_error($categories)) { | |
// Get the first category assigned to the post | |
$category = reset($categories); | |
// Get ancestors of the category (parent categories) | |
$ancestors = get_ancestors($category->term_id, 'category'); | |
// If the category has no ancestors, it is a top-level category | |
if (empty($ancestors)) { | |
// Return the ID of the top-level category | |
return $category->term_id; | |
} else { | |
// Return the ID of the top-level parent category | |
return end($ancestors); | |
} | |
} else { | |
// If no terms are assigned, return 0 | |
return 0; | |
} | |
} | |
} | |
new Get_Ancestor(); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment