Skip to content

Instantly share code, notes, and snippets.

@kingkool68 kingkool68/tags.php forked from chriscoyier/tags.php
Last active Aug 22, 2019

Embed
What would you like to do?
<?php
class CTF_Register_Taxonomies {
/**
* Initialize the class
*/
public function __construct() {
add_action( 'init', array( $this, 'tags_support_all' ) );
add_action( 'pre_get_posts', array( $this, 'tags_support_query' ) );
}
/**
* Associate tags with the Page post type
*/
public function tags_support_all() {
register_taxonomy_for_object_type( 'post_tag', 'page' );
}
/**
* Ensure all post types that support tags are included in the main query
*
* @param WP_Query $wp_query
*/
public function tags_support_query( $wp_query ) {
// Bail if the query isn't the main query or the query is happening in the WordPress admin
if ( ! $wp_query->is_main_query() || is_admin() ) {
return;
}
if ( is_tag() ) {
// Get the taxonomy details of the post_tag taxonomy
$taxonomy = get_taxonomy( 'post_tag' );
// Sanity check so we don't throw any PHP errors
if ( ! empty( $taxonomy->object_type ) ) {
// Query for any post type that is associated with the post_tag taxonomy
$wp_query->set( 'post_type', $taxonomy->object_type );
}
}
}
}
// Kick things off
new CTF_Register_Taxonomies();
@kingkool68

This comment has been minimized.

Copy link
Owner Author

commented Aug 22, 2019

The original gist had if ($wp_query->get('tag')) $wp_query->set('post_type', 'any');

$wp_query->get('tag' would check if the query contains a slug of a tag and if so determines that yes this is a tag page. A better way would be to use [is_tag()](https://developer.wordpress.org/reference/functions/is_tag/) whose purpose is to determines whether the query is for an existing tag archive page.

We should also check to make sure the query is the main query and not a secondary loop on the page using $wp_query->is_main_query(). We also don't want to modify the behavior if the loop is being performed in the admin section of WordPress which we check with is_admin().

$wp_query->set('post_type', 'any'); would be fine for most situations. It's a good idea to be a little more specific and set the query to look in all of the post types that are associated with the post_tag taxonomy which is what is in $taxonomy->object_type.

We could go a step further and use $wp_query->get( 'post_type' ); to get all of the current post types being queried and then only adding new post types. Currently if there was another part of the theme or a plugin modifying the query our changes would overwrite their changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.