問題描述
我有一個典型的短碼在頁面上打印一些 html 。短碼只能在訪問者登錄的頁面上使用。
作為一個單獨的操作,我一直在使用自定義字段來觸發執行該測試的操作,然後執行重定向。
但是我想知道是否可以將該動作與短碼結合起來,擺脱自定義字段。
IOW:我可以在標頭中的某些標籤中製作短碼打印代碼,以測試訪問者是否登錄,如果不是,請將其重定向到主頁。
例如。
function jchForm() {
add_action( 'no idea where this would go', 'my_redirect_function' );
$s ='<div class="clearboth">';
$s .='<form id="my_form" action="" method="post">';
$s .='<p><label>Your Name</label><input id="user_name" type="text" name="user_name" class="text" value="" /></p>';
$s .='<p><label>Your Email Address</label><input id="user_email" type="text" name="user_email" class="text" value="" /></p>';
$s .='<p><input type="submit" id="my_submit" name="submit" value="Register" /></p>';
$s .='</form>';
$s .='</div>';
return $s;
}
更新:我試過這個,根據 has_shortcode() 函數引用,但儘管它觸發,$ post 總是返回 NULL 。如何獲得這個打印 – 在任何其他 html 之前,但是 – 後 – 查詢抓取 $ post?
function custom_shortcode_script() {
global $post;
if( is_user_logged_in() && has_shortcode( $post->post_content, 'jchForm') ) {
var_dump($post->post_content); // always prints NULL
wp_redirect( '/someplace');
}
}
add_action( 'init', 'custom_shortcode_script' );
最佳解決方案
短碼功能只有在可視化編輯器的內容被處理和顯示時才會被調用,所以你的短代碼功能什麼都不會足夠早。
看看 has_shortcode 功能。如果你早點提前發送標題,並足夠遲到要設置的查詢,您可以檢查內容是否包含您的短代碼,然後重定向。 template_redirect 鈎子很方便,因為它是關於在您的主題將輸出發送到瀏覽器之前調用的最後一個鈎子,這會觸發 PHP 發送頭文件。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。