1 回答

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
您的 ajax 調(diào)用沒有$post
來自 ajax 請求的頁面的全局內(nèi)容,因此get_the_ID()
應(yīng)該是 false 并且get_post_meta( get_the_ID(), '_t5_extra_box', TRUE )
也將是 false。此外,您正在調(diào)用do_shortcode('[extra]')
(無內(nèi)容),因此$content
回調(diào)內(nèi)將是一個(gè)空字符串。所以return wpautop(get_post_meta( get_the_ID(), '_t5_extra_box', TRUE).$content);
就變成了return wpautop('');
一個(gè)空字符串。根據(jù)您的代碼,我希望您的data
響應(yīng)始終為空字符串。
為了解決這個(gè)問題,我將添加一個(gè)額外的 ajax post 數(shù)據(jù)項(xiàng)以及告訴回調(diào)$post_id
應(yīng)該是什么的操作。這是最原始的方式。您可能想要添加隨機(jī)數(shù)或其他一些安全措施(但這可能與您原來的問題無關(guān))。
更新
我還沒有對此進(jìn)行測試,您可能想要以不同的方式進(jìn)行操作,但這里有一個(gè)選擇。最終,您只需要一種方法來從原始請求中獲取$post_id
并將其傳遞給 ajax 調(diào)用。由于您已經(jīng)通過 ajax url 傳遞wp_localize_script
,我只需在那里添加另一個(gè) JavaScript 變量。
jQuery
jQuery(document).ready(function ($) {
$('#extra').on('click', function () {
$.ajax({
type: "POST",
url: my_ajaxurl,
data: {
action: 'process_shortcode_on_click_action',
post_id: my_postid,
},
success: function (data) {
console.log("Success");
},
error: function (errorThrown) {
console.log("Error");
}
});
})
})
函數(shù).php
add_action('wp_enqueue_scripts', 'add_my_script');
function add_my_script () {
wp_enqueue_script(
'extra-script', // name your script so that you can attach other scripts and de-register, etc.
get_template_directory_uri() . '/js/script.js', // this is the location of your script file
array('jquery') // this array lists the scripts upon which your script depends
);
wp_localize_script('extra-script', 'my_ajaxurl', admin_url('admin-ajax.php'));
wp_localize_script('extra-script', 'my_postid', get_the_ID());
}
add_action('wp_ajax_process_shortcode_on_click_action', 'process_shortcode_on_click_ajax');
add_action('wp_ajax_nopriv_process_shortcode_on_click_action', 'process_shortcode_on_click_ajax');
function process_shortcode_on_click_ajax ()
{
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
if (empty($post_id = $_POST['post_id']) || !is_numeric($post_id)) {
wp_die('Post ID is Invalid', 400);
}
echo do_shortcode("[extra post_id='{$post_id}']");
wp_die();
}
add_shortcode('extra', 't5_extra_content');
function t5_extra_content ($attributes, $content = '')
{
$defaults = [
'post_id' => get_the_ID(),
'cap' => 'edit_posts'
];
$args = shortcode_atts($defaults, $attributes);
if (!current_user_can($args['cap']) || empty($args['post_id'])) {
return ''; // or some message on fail
}
return wpautop(get_post_meta($args['post_id'], '_t5_extra_box', TRUE) . $content);
}
- 1 回答
- 0 關(guān)注
- 118 瀏覽
添加回答
舉報(bào)