Viewing 1 replies (of 1 total)
  • Hi mkiisoft,

    I’m not the author but I got a nice answer in this same forum so I’m glad if I can help him/her/them.

    You can simply create a new WordPress AJAX call ( http://codex.ww.wp.xz.cn/AJAX_in_Plugins ) in your theme and call it with the post ID to get the views count.

    Here’s an example.

    In your functions.php you register the AJAX callback, here it has the name ‘ajax_post_views_counter’.

    function ajax_post_views_counter() {
        $post_id = intval( $_GET['post_id'] );
        if ( empty( $post_id ) ) {
            echo json_encode( (object) array( 'views' => -1, 'error' => 'Empty post ID' ) ); die();
        }
        if ( ! function_exists( 'pvc_get_post_views' ) ) {
            echo json_encode( (object) array( 'views' => -1, 'error' => 'Plugin not loaded' ) ); die();
        }
        echo json_encode( (object) array( 'views' => pvc_get_post_views( $post_id ) ) );
        die();
    }
    add_action( 'wp_ajax_nopriv_ajax_post_views_counter', 'ajax_post_views_counter' ); // Enable also when outside admin
    add_action( 'wp_ajax_ajax_post_views_counter', 'ajax_post_views_counter' );

    Then as explained in that link, you’ve to call admin-ajax.php with the name of the callback as the action parameter and then all the parameters you need, in this example we are using post_id.

    The code below is ran from inside a WordPress loop where you can access the current post id and access to the admin_url helper, it will popup an alert with information on click.
    The code will generate a link similar to
    http://<YOUR_DOMAIN>/wp-admin/admin-ajax.php?action=ajax_post_views_counter&post_id=<POST_ID_HERE>
    so if you’re not using WordPress to generate it, provided you’ve the post ID you can call it from anywhere.

    <button id="testAjaxCount">Test get count</button>
    <script>
    jQuery(function ( $ ) {
        $( '#testAjaxCount').on( 'click', function() {
            $.get( '<?php echo admin_url( 'admin-ajax.php' ) ?>?action=ajax_post_views_counter&post_id=<?php the_ID() ?>', function( result ) {
                if ( ! result.error )
                    alert( 'Views: ' + result.views );
                else
                    alert( 'Error: ' + result.error );
            }, 'json' );
        });
    });
    </script>

    Hope it helps.

    Cheers,
    Guillermo

Viewing 1 replies (of 1 total)

The topic ‘get views for a REST API’ is closed to new replies.