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() {
             __('Reco Personalisation','wpb_widget_per_person'), 
             array( 'description' => __( 'Content widget', 'wpb_widget_per_person' ), ) 
       public function widget( $args, $instance ) { ?>
                    var url = jQuery(this).attr('href');
                    url: '<?php echo admin_url('admin-ajax.php'); ?>',
                    method: "POST",
                    contentType: 'application/json',
                    data: ({
                        action: "get_prev_ajax_handler",
                        url: url
                    success: function (response){

       <?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?

  • please properly format your question, and make sure it is actually readable and it is possible to understand it. in addition add all relevant code, and debugging effort you have done. Commented Jul 10, 2017 at 6:50

2 Answers 2


the another way to get the post_id by clicking on the link is to add a data-attribute to the link. e.g; data-post-id="'.get_the_ID().'"

your html code should look like

<a href="#link" data-post-id="47">Link</a>

then in your js code above the ajax call

var post_id = jQuery(this).attr('data-post-id');

and pass this in your data object to the ajax call.

data: ({
     action: "get_prev_ajax_handler",
     url: url,
     post_id: post_id,

now you can get the post_id with $_POST['post_id'] or print_r() the $_POST array()


Your action in JQuery and and hook action is not matching. It should be:

add_action('wp_ajax_get_prev_ajax_handler', 'get_prev_ajax_handler'); 
add_action( 'wp_ajax_nopriv_get_prev_ajax_handler', 'get_prev_ajax_handler' );

Also get get_prev_ajax_handler function outside Reco_Person class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.