1

I want to send an ajax request and want to process it if the user is logged in. Therefore I want to use following two hooks, but I am not sure if I am using them correctly.

Is it correct to use same function take_action_function for the both hooks, and then check in the function if the user is logged in or not? Or should I create two different functions, one for the take action and other one just to return the message that user should be logged in?

add_action('wp_ajax_nopriv_test-action', 'take_action_function');
add_action('wp_ajax_test-action', 'take_action_function');

function take_action_function(){
    if ( is_user_logged_in() ){
       echo "success";
       die;
    } else {
        echo "not logged";
        die;
    }
}
  • 1
    It doesn’t really matter. Do you get any problem with one method? – fuxia Nov 3 '13 at 16:33
  • No, not any problem but I just thought if there's any standard/preferred coding practice. – enam Nov 3 '13 at 16:36
  • I'd leave it as is.... looks good to me. – helgatheviking Nov 3 '13 at 17:02
  • Have you considered using REST API endpoints instead? – Tom J Nowell Apr 27 '18 at 19:54
4

It depends on what exactly you want to do. If you want to show just a short message, use the same callback for both.

But if you need completely different objects and load different additional files depending on the log-in status, use separate callbacks.

Basic example, probably not a recommended implementation. :)

class Ajax_Controller {

    public function __construct( $action ) {

        add_action( "wp_ajax_nopriv_$action", array ( $this, 'logged_out' ) );
        add_action( "wp_ajax_$action",        array ( $this, 'logged_in' ) );
    }

    public function logged_out() {

        require_once __DIR__ . '/Logged_Out_Data_Interface.php';
        require_once __DIR__ . '/Logged_Out_Data.php';
        require_once __DIR__ . '/Logged_Out_View.php';

        $data = new Logged_Out_Data;
        $view = new Logged_Out_View( $data );
        $view->render();
    }

    public function logged_in() {

        require_once __DIR__ . '/Logged_In_Data_Interface.php';
        require_once __DIR__ . '/Logged_In_Data.php';
        require_once __DIR__ . '/Logged_In_View.php';

        $data = new Logged_In_Data;
        $view = new Logged_In_View( $data );
        $view->render();
    }
}

Look at your use case, be pragmatic. When in doubt, compare the performance and the complexity of both approaches.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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