I have an interesting task. I've wrote custom 404 handler for wordpress and extracted an URL. Than, after doing some logic I've got a wordpress post ID that I need to display instead of 404 page.
How can I display a wordpress post page instead of 404 page? The only thing I can think of is do
echo wp_remote_fopen(....<post permalink>...);
But is there any alternative way to do that? Thanks
I was not able to do this by rewriting template's 404.php. And also I think that is would very template-depended. Instead I've managed to display a post by using template_redirect action. The code of plugin function looks like this:
function func_404_redirect($query){
global $wp_query;
$post = get_post(2);
$wp_query->queried_object = $post;
$wp_query->is_single = true;
$wp_query->is_404 = false;
$wp_query->queried_object_id = $post->ID;
$wp_query->post_count = 1;
$wp_query->current_post=-1;
$wp_query->posts = array($post);
}
add_filter('template_redirect','func_404_redirect');
Instead of a 404 handler you can create a 404.php page in you theme (or child), see reference - from there you can do anything you like: load a list of posts, load a single post, etc.
The code I use in my theme:
<?php
global $my_theme;
$content_id = $my_theme->option( OPT_GENERAL, '404_page_id', TRUE );
$my_theme->prepare( $content_id, '404' );
get_header();
?>
<!-- [BEGIN 404] -->
<div class="row">
<?php
get_sidebar( 'left' );
?>
<div id="primary" class="content-area <?php echo $class; ?>">
<main id="main" class="site-main" role="main">
<section class="error-404 not-found">
<?php
// Load the content from the selected page
$content_loaded = FALSE;
if( $content_id > 0 )
{
$query = new WP_Query( array( 'page_id' => $content_id ) );
while( $query->have_posts() )
{
$query->the_post();
get_template_part( 'content', 'page' );
$content_loaded = TRUE;
}
wp_reset_postdata();
}
// Fallback content
if( !$content_loaded )
{
?>
<header class="page-header">
<h4 class="page-title well text-center"><?php _e( 'Page not found', 'my_theme' ); ?></h4>
</header>
<div class="page-content alert alert-danger text-center">
<p><?php _e( 'It looks like nothing was found at this location', 'my_theme' ); ?></p>
</div>
<?php
}
?>
</section>
</main>
</div>
<?php get_sidebar( 'right' ); ?>
</div>
<?php get_footer(); ?>
<!-- [END 404] -->