簡體   English   中英

如何在標題發送后重定向頁面? WordPress的

[英]How can redirect the page after the header sent? Wordpress

我在wordpress上制作了一個插件。 當用戶單擊主頁上的視圖發布按鈕時,它將檢查某些條件以允許用戶查看帖子。

如果不允許用戶查看帖子,頁面將被重定向到錯誤頁面。

但是,問題在於,插件是由快捷方式運行的,因此該函數將在加載后發布頁面后運行。 它出來了這個錯誤Cannot modify header information - headers already sent by (output started at /home/wordpress/wp-includes/class.wp-styles.php:237)

並且在標題發送后如何重定向網址?

此外,我需要使它成為捷徑。

多謝。

這是我的代碼:

   function add_post_condition_vpc($atts, $content = null)
    {      

     $userPoint = getPointFromDb();
   if($userPoint > 50)
                  {           

                     //redirect the the page to the view-post-direct-page.php
                     $page_file_temp = $_SERVER["PHP_SELF"];
                     $url= dirname($page_file_temp) . "/view-post-direct-page.php";
                     header("Location: $url ");
                     return "redirect";

                  }
  } 

  add_shortcode('view_post_lmc', 'add_post_condition_vpc');

和分享按鈕,我使用此代碼獲取當前發布的網址:

$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

然后我在帖子上添加短代碼。


我找到了解決方案。

這是我的代碼:

//redirect the the page to the view-post-direct-page.php
$page_file_temp = $_SERVER["PHP_SELF"];
$url= dirname($page_file_temp) . "/view-post-direct-page.php";

$string = '<script type="text/javascript">';
$string .= 'window.location = "' . $url . '"';
$string .= '</script>';

return $string;

使用Javascript以避免header again發送header again

functions.php中添加:

function app_output_buffer() {
    ob_start();
} // soi_output_buffer
add_action('init', 'app_output_buffer');

在這里找到它: https//tommcfarlin.com/wp_redirect-headers-already-sent/

為什么使用短代碼進行此檢查?

我認為你最好使用Wordpress的init hook 將其添加到functions.php或插件文件中,並在加載頁面之前執行檢查:

function add_post_condition_vpc() {      
     $userPoint = getPointFromDb();

     if($userPoint > 50) {           
           $page_file_temp = $_SERVER["PHP_SELF"];
           $url= dirname($page_file_temp) . "/view-post-direct-page.php";
           header("Location: $url ");
           exit(); // just exit, return is not needed here
        }
} 

add_action('init', add_post_condition_vpc);

如果帖子附加了某種標簽,你可以在這個功能中執行檢查。 當它執行時,您運行用戶點檢查。 這樣您就不需要短代碼標簽。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM