1 回答
TA贡献1797条经验 获得超6个赞
您的 ajax 调用没有$post
来自 ajax 请求的页面的全局内容,因此get_the_ID()
应该是 false 并且get_post_meta( get_the_ID(), '_t5_extra_box', TRUE )
也将是 false。此外,您正在调用do_shortcode('[extra]')
(无内容),因此$content
回调内将是一个空字符串。所以return wpautop(get_post_meta( get_the_ID(), '_t5_extra_box', TRUE).$content);
就变成了return wpautop('');
一个空字符串。根据您的代码,我希望您的data
响应始终为空字符串。
为了解决这个问题,我将添加一个额外的 ajax post 数据项以及告诉回调$post_id
应该是什么的操作。这是最原始的方式。您可能想要添加随机数或其他一些安全措施(但这可能与您原来的问题无关)。
更新
我还没有对此进行测试,您可能想要以不同的方式进行操作,但这里有一个选择。最终,您只需要一种方法来从原始请求中获取$post_id
并将其传递给 ajax 调用。由于您已经通过 ajax url 传递wp_localize_script
,我只需在那里添加另一个 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");
}
});
})
})
函数.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 关注
- 65 浏览
添加回答
举报