Support » Developing with WordPress » How can we show custom content, header, title for specific urls using plugin

  • manjiri123

    (@manjiri123)


    I have tried below code for showing custom content using hook like the_content, the_title, the_post for the pages which is not exist nor created by user.

    
    add_action('template_redirect', 'override_404');
    
    function override_404() {
        global $wp, $wp_query;
        
        if (is_404() && $wp->request == 'my-whitelisted_request') {        
            $template = get_index_template();
            $template = apply_filters( 'template_include', $template );
            include $template;
            die;
        }
    }
    

    So instead of 404 page I want to display custom content based on url.

    I have not getting the output as index.php having code like have_posts() to true else redirecting to 404 page.

    Is there a way to make have_posts() true in some cases ?

    • This topic was modified 1 month ago by manjiri123.
Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    If you’re overriding the template anyway, why not go to a custom template and output what you want and disregard the main query and its have_posts() method? The index template isn’t working in a 404 situation because it’s relying upon the main query that couldn’t find anything. You’d first need to make a new query for the content you want. You could use query_posts() in your callback to redo the main query so the index template will work.

    You could avoid needing any template redirect by altering your theme’s 404.php template to output what you want. If you make another query to get desired content, you’ll want a fallback 404 scheme in case that query should also fail to find anything.

Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.