2015-11-13 49 views
1

我有一個有趣的任務。 我已經寫了wordpress的自定義404處理程序,並提取了一個URL。 比做了一些邏輯後,我得到了一個wordpress post ID,我需要顯示而不是404頁面。如何顯示wordpress文章而不是404頁面?

如何顯示WordPress頁面而不是404頁面? 我能想到的唯一的事情就是做

echo wp_remote_fopen(....<post permalink>...); 

但是它有什麼替代的方式來做到這一點? 感謝

回答

0

我不能通過重寫模板的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'); 
0

取而代之的是404處理器,你可以在你的主題(或子女),見reference創建一個404.php頁面 - 從那裏你可以做任何你喜歡的:加載信息的列表,加載單篇文章,等

+0

聽起來是個好主意,我會在幾個小時嘗試。 – 1099511627776

+0

不,我無法在模板的404.php中做到這一點。相反,我設法做到這一點通過template_redirect行動 – 1099511627776

+0

在模板中我用404.php加載一個自定義帖子(從ID),它工作得很好 – Mat

1

我在主題使用代碼:

<?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] --> 
+0

我同意,這可能是一種做我想做的事情的方式。現在可以請你看看我的回答,並說出它是否可用? – 1099511627776

+0

IMO 404.php是正確的選擇。使用該過濾器可以,但是從[template_redirect](https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect)過濾器的引用中,它應該用於在某些情況下重定向到另一個頁面,而不是過濾帖子查詢 – Mat

相關問題