0

I am going to track number of plays of a video in my site by both visitors and users. Whenever the video starts playing I am using JavaScript for the event handling in the frontend and write to wp_options or wp_usermeta to track these interactions.

I was going to make an AJAX request to the wp_ajax_$action and wp_ajax_nonpriv_$action hooks but I'd like to use this small task as an opportunity to experiment with the new REST API since I heard it is going to replace the old wp-admin/admin-ajax.php way of doing it on the long run.

How should I approach this?

1 Answer 1

1

In WP REST API v2 use the permission_callback found in the Adding Custom Endpoints Docs.

<?php
add_action( 'rest_api_init', function () {
    register_rest_route( 'myplugin/v2', '/author/(?P<id>\d+)', array(
        'methods' => 'GET',
        'callback' => 'my_awesome_func',
        'args' => array(
            'id' => array(
                'validate_callback' => 'is_numeric'
            ),
        ),
        'permission_callback' => function (WP_REST_Request $request) {
            if ( current_user_can( 'edit_others_posts' ) ) {
                return true;
            } 
            else { 
                return false;
            }
        }
    ) );
} );
2
  • To clarify: since I want all requests to be processed, regardless of the users permissions, I would make the permission callback always return true, correct? 'permission_callback' => '__return_true'
    – Jan Beck
    Commented Dec 21, 2015 at 15:22
  • 1
    Yes, or just leave off permission_callback'.
    – jgraup
    Commented Dec 21, 2015 at 15:32

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.