Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

Wordpress single template not having post data when loaded as a template

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...