Reputation: 877
Adding tags to WordPress pages
I try to display both posts and pages that are tagged with the same tag when I'm on a WordPress tag page. I'm using some custom code to be able to add the tag functionality to WordPress pages. Adding a tag to a page works and I can also display the tag on the page when I'm using <?php the_tags(); />
in a page template.
I'm using this code (in my child theme functions.php) to register the tag functionality to pages:
// Add tag support to pages
function tags_support_all() {
register_taxonomy_for_object_type('post_tag', 'page');
}
add_action('init', 'tags_support_all');
The issue - Pages with tags are not being displayed on the tag page
I can't seem to find a way to get these pages displayed on the tag page. It only shows the posts that are tagged with the same tag. No pages. I use the code below to try and update the pre_get_posts query by setting the post_type to 'any'. It's an (old) snippet that I found on Google why I was searching for a solution. I'm not sure if this is still the way to go, but I couldn't find any working alternatives.
// Display all post types on tag pages
function tags_support_query($wp_query) {
if ($wp_query->get('tag')) {
$wp_query->set('post_type', 'any');
}
}
add_action('pre_get_posts', 'tags_support_query');
Any ideas on how to get this working?
Some extra information:
Upvotes: 0
Views: 2730
Reputation: 20954
Create a new file that you can use for all Tags and call it tag.php
. This will allow all Tag related archive pages to be rendered by this file. Other categories and archives will remain untouched.
In this new file copy all contents of index.php
but add the following code in the top of the file.
/**
* Get the Term ID of the current term.
*/
$term = get_queried_object();
$term_id = $term->term_id;
/**
* Get all posts and pages with the current term.
*/
$args = array(
'post_type' => array('post', 'page'),
'posts_per_page' => -1,
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'post_tag',
'field' => 'term_id',
'terms' => [$term_id]
)
)
);
/**
* Create a new query.
*/
$query = new WP_Query($args);
Then replace all occurences where the following occurs:
if ( have_posts() ) {
// replace with
if ( $query->have_posts() ) {
,
while ( have_posts() ) {
// replace with
while ( $query->have_posts() ) {
and
the_post();
// replace with
$query->the_post();
Then after the closing bracket of the while
loop, add wp_reset_postdata();
to ensure that the post data related to the page has been reset. (otherwise the latest post in the loop will be considered the post of the page).
This should (at least) give you access to the posts and pages that have the post_tag
term that corresponds with the page.
Upvotes: 4