[英]How can I display wordpress post instead of 404 page?
我有一个有趣的任务。 我已经为wordpress编写了自定义404处理程序,并提取了一个URL。 然后,在做一些逻辑后,我需要显示一个wordpress帖子ID,而不是404页面。
如何显示wordpress发布页面而不是404页面? 我唯一能想到的就是
echo wp_remote_fopen(....<post permalink>...);
但是,还有其他替代方法吗? 谢谢
我无法通过重写模板的404.php来做到这一点。 而且我认为这将非常依赖模板。 相反,我设法通过使用template_redirect操作来显示帖子。 插件功能的代码如下所示:
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');
我在主题中使用的代码:
<?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] -->
您可以在主题(或子主题)中创建404.php页面,而不是404处理程序,请参阅参考资料 -从那里您可以做任何您想做的事情:加载帖子列表,加载单个帖子等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.