我正在单击锚标记中定义的链接并获取url。我想将url\\u中的此url传递给postid($\\u POST[\'url\'),它返回我的ID。
到目前为止,我所做的一切都在工作,除了对admin ajax的ajax调用,以传递url来获取ID
步骤1:在widget()函数中创建小部件
步骤2:单击时调用get\\u prev\\u ajax\\u handler()函数,并希望使用url\\u to\\u postid($\\u post[\'url\')获取该链接的帖子ID;
function Reco_load_widget() {
register_widget( \'Reco_Person\' );
}
add_action( \'widgets_init\', \'Reco_load_widget\' );
class Reco_Person extends WP_Widget {
function __construct() {
parent::__construct(
\'wpb_widget_per\',
__(\'Reco Personalisation\',\'wpb_widget_per_person\'),
array( \'description\' => __( \'Content widget\', \'wpb_widget_per_person\' ), )
);
}
public function widget( $args, $instance ) { ?>
<script>
jQuery(function(){
jQuery(\'a\').click(function(){
var url = jQuery(this).attr(\'href\');
jQuery.ajax({
url: \'<?php echo admin_url(\'admin-ajax.php\'); ?>\',
method: "POST",
contentType: \'application/json\',
data: ({
action: "get_prev_ajax_handler",
url: url
}),
success: function (response){
console.log(response);
}
});
});
});
</script>
<?php }
public function get_prev_ajax_handler() {
return url_to_postid($_POST["url"]);
}
}
add_action(\'wp_ajax_get_prev\', \'get_prev_ajax_handler\'); // add action for logged users
add_action( \'wp_ajax_nopriv_get_prev\', \'get_prev_ajax_handler\' );
但这个钩子不起作用。我是否使用错误的参数在错误的位置调用了add\\u操作?
SO网友:Aamer Shahzad
另一种获取post_id
通过单击link
是添加data-attribute
到链接。e、 g;data-post-id="\'.get_the_ID().\'"
您的html代码应该如下所示
<a href="#link" data-post-id="47">Link</a>
然后在ajax调用上方的js代码中
var post_id = jQuery(this).attr(\'data-post-id\');
把这个传给你
data
对象调用ajax。
data: ({
action: "get_prev_ajax_handler",
url: url,
post_id: post_id,
}),
现在您可以获得
post_id
具有
$_POST[\'post_id\']
或
print_r()
这个
$_POST
array()