0
-Parent-category
    -Sub-category

Want to get parent ID when on the current post of sub-category. Created a custom post type and custom taxonomies for that post type. Created a category and assigned another category to have the first category as a parent. I'm listing all posts of that parent category on the parent category page when a particular post is clicked it opens the single-custom_post_type.php and want to get the parent category ID on the single-custom_post_type.php so I can add a sidebar with all the sibling's post with the same parent category.

Any help?

$args_docs   =   array(
    'post_type'         =>  Documents::DOCUMENTS_TYPE_KEY,
    'posts_per_page'    =>  -1,
    'tax_query' => array(
        array(
            'taxonomy'  =>  DocumentsTaxonomy::DOCUMENTS_TAXONOMY_KEY,
            'field'     =>  'term_id',
            'terms'     =>  9, // <- I want here to add the parent category ID dynamically,so whenever we are currently on a post it gives that posts parent category ID
        ),
    ),
);
1

Get Object Terms : Retrieves an array of WP_Term object associated with the given post, in the supplied taxonomies.

Term object ( WP_Term )offers some handy information. For example,

Gives you term slug: e.g.: term-slug-example

$slug = $term->slug;

Gives you term name: e.g. Term Name Example

$name = $term->name;

Gives you term description: e.g. This is my new cool custom term.

$desc = $term->description;

But unfortunately lacks a link value. So use Get Term Link to generate a permalink for a taxonomy term archive.

$term_link = get_term_link( $term);

So your finalcode should look like this:

$sub_cats = wp_get_object_terms( $post->ID, DocumentsTaxonomy::DOCUMENTS_TAXONOMY_KEY, ); // array of categories associated with current post


$args_docs   =   array(
    'post_type'         =>  Documents::DOCUMENTS_TYPE_KEY,
    'posts_per_page'    =>  -1,
    'tax_query' => array(
        array(
            'taxonomy'  =>  DocumentsTaxonomy::DOCUMENTS_TAXONOMY_KEY,
            'field'     =>  'term_id',
            'terms'     =>  $sub_cats[0]->parent, 
        ),
    ),
);
  • 1
    Thanks man! You helped a lot. – TestimiUEB Apr 17 at 13:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.