2014-09-26 111 views
4

我想使用開關按鈕運行短代碼。如果開關處於「開」狀態,我稱之爲短碼,如果它處於「關」狀態,則打給另一個短碼。使用AJAX調用wordpress短代碼

作爲測試我打過電話,在與AJAX一個單一鏈路上點擊一個短代碼,它給了我這樣的:

文件「頁面recherche.php」:

<a href="" id="clicklien">CLICK HERE</a> 


<script> 
$("#clicklien").click(function(e){ 
     e.preventDefault(); 
    $.ajax({ 
    url: 'http://www.capitainebar.com/wp-content/themes/Capitaine-Bar/shortcode-recherche.php', 
    success: function (data) { 
     // this is executed when ajax call finished well 
     console.log('content of the executed page: ' + data); 
     $('body').append(data); 

    }, 
    error: function (xhr, status, error) { 
     // executed if something went wrong during call 
     if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted 
    } 
}); 

}); 
</script 

文件名爲是「shortcode-recherche.php」:

<?php echo do_shortcode('[search-form id="1" showall="1"]'); ?> 

結果是致命錯誤。就好像代碼運行在「shortcode-recherche.php」而不是「page-recherche.php」中。

請注意,如果我不通過AJAX調用將短代碼直接寫入我的頁面,短代碼工作正常。

你可以看到the result here

+0

你能發佈你收到的錯誤嗎? – Dez 2014-09-26 23:00:44

+0

致命錯誤:調用未定義的函數do_shortcode()在/homepages/1/d543902707/htdocs/wp-content/themes/Capitaine-Bar/shortcode-recherche.php在線1 – 2014-09-26 23:38:03

回答

2

當你調用一個PHP文件直接,WordPress的不參與。這意味着像do_shortcode()這樣的函數甚至不存在。

相反,您需要請求一個被WordPress捕獲的文件(即使通常是404)。然後,讓你的插件知道URL。你可以用查詢變量(簡單)或重寫規則(困難,漂亮)來做到這一點。例如:

查詢變量:example.org/?custom_shortcode=gallery

Rerwrite規則:example.org/custom_shortcode/gallery/


無論您選擇的選項,你的插件需要,當你訪問這個URL並攔截其瞭解。完成後,您需要退出腳本以防止WordPress嘗試顯示404頁面。

這裏是一個例子,你可以簡單地將它放入你的functions.php文件。

function shortcode_test() { 
    if (!empty($_REQUEST['shortcode'])) { 
    // Try and sanitize your shortcode to prevent possible exploits. Users typically can't call shortcodes directly. 
    $shortcode_name = esc_attr($_REQUEST['shortcode']); 

    // Wrap the shortcode in tags. You might also want to add arguments here. 
    $full_shortcode = sprintf('[%s]', $shortcode_name); 

    // Perform the shortcode 
    echo do_shortcode($full_shortcode); 

    // Stop the script before WordPress tries to display a template file. 
    exit; 
    } 
} 
add_action('init', 'shortcode_test'); 

你可以通過這個訪問您的網站測試這個加在URL的末尾:

?shortcode=gallery

這應該顯示擴展爲HTML畫廊簡碼。一旦這個工作正常,只需將其綁定到現有的AJAX功能。

+0

好吧,我終於明白了......謝謝很多爲您的幫助! – 2014-09-27 11:02:42

+0

使用'?shortcode = search-form',它會在/ homepages/1/d543902707/htdocs/wp-content/plugins/profi-search-filter/includes/shortcode中向我返回這個警告:非法字符串偏移量'id'。在線4上的php。 如何在您給我的網址中指定我的簡碼的ID? – 2014-09-27 11:33:27

+0

你好,請你看看我的問題:http://stackoverflow.com/questions/41248786/wordpress-execute-do-shortcode-inside-ajax-function – 2016-12-21 07:16:16