1

I know I can access to posts with this url structure : mysite.com/?p=X where X is the post ID. It's convenient because it will work even if the permalink for this post is modified.

But you you now if there is a similar structure for terms (categories, tags...) ?

I tried

?t=term_id

But it doesn't work.

Thanks

1

1 Answer 1

2

Well if you are referring to what are the query string keys are, it will depend on the taxonomy you are working with, for

  • categories: you are looking for ?cat=cat_id
  • tags: you are looking for ?tag=tag_slug
  • custom taxonomy: it depends on the slug of the tax but it will look like ?taxonomy_slug=item_slug

Check the definition of the default WP query vars keys for more info

EDIT

As per you comment, I thought I would share this too. If you need/want to search by term_id (regardless of custom tax or not) you would need to add a custom query string (query vars) and modify the main query to do so.

Here's how you could do this

// Add your custom query var so WP can listen for that query string too
add_filter( 'query_vars', 'my_add_custom_query_vars' );
function my_add_custom_query_vars( $vars ){
  $vars[] = 'my_var';
  return $vars;
}


// Then modify the query to include all taxonomies, searching by tax ID
add_action( 'pre_get_posts', 'my_custom_query' );
function my_custom_query( $query ){
  $my_id = absint( get_query_var( 'my_var' ) ); // retrieve the var defined above

  $tax_query_args = array(
    array(
      'field'         => 'term_taxonomy_id',
      'terms'         => $my_id,
    ),
  );

  $query->set( 'post_type', 'any' );
  $query->set( 'tax_query', $tax_query_args );

}

My example could be expanded to listen for multiple term_id so you could use a query string like ?my_var=1,2,3 to return any posts within term_id 1 OR 2 OR 3 or ?my_var=1+2+3 to return any posts within term_id 1 AND 2 AND 3. But as a general basic concept, this is how you would do it.

3
  • So for custom taxonomy, you can't use the term id ?
    – Matthieu
    Aug 27, 2016 at 13:24
  • it doesn't look that way, if you look further down at line 1897 into query.php, you'll see that for custom taxonomy, the slug is used, as opposed to categories (line 1956) the term_id is used instead. If you really need/want to look for content by term_id you' d have to make your custom query arg and modify the main $wp_query accordingly
    – bynicolas
    Aug 27, 2016 at 17:33
  • 1
    @Matthieu updated my answer to show how to use a custom query to get custom taxonomies by term_id
    – bynicolas
    Aug 27, 2016 at 18:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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