I have a custom template for posts (single.php) which works fine when accessing articles under normal circumstances:
domain.com/news/article-1/
But when I load single.php on a dummy news page (based on another query) I keep getting false when checking have_posts(). For example:
domain.com/category/news/article-2/
routing.php
(This is included in functions.php)
/**
* News item page
*/
if ($category_key && $news_key && count($a_current_url) - $news_key == 3):
$news_slug = $a_current_url[$news_key + 1];
add_action('template_redirect', 'override404', 0);
add_filter('template_include', function () {
get_template_part('single');
});
endif;
In this piece of code I check if it is the specific news page that needs the single template to be included. I also set the global $news_slug variable.
single.php
So, since have_posts is always empty as there is no post loaded because of the 404, I need to load this myself:
if (!have_posts()):
$args = [
'name' => $news_slug,
'post_type' => 'post',
'post_status' => 'publish',
'numberposts' => 1,
'suppress_filters' => 0,
];
$post = get_posts($args);
setup_postdata($post[0]->ID);
endif;
But no matter what I try, have_posts() remains false.
What am I doing wrong here?
question from:
https://stackoverflow.com/questions/66062855/wordpress-single-template-not-having-post-data-when-loaded-as-a-template 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…