I am clicking on the link define in the anchor tag and fetching the url. I want to pass this url in url_to_postid($_POST['url']) which returns me ID.
What I have done till far now is everything working except the ajax call on admin-ajax to pass url to fetch ID
Step 1 : Created a widget in widget() function
Step 2 : Calling get_prev_ajax_handler() function on click and want to get the post ID of that link using url_to_postid($_POST['url']);
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' );
But this hook is not working. Did I invoke add_action at wrong place with wrong parameter?