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;
}
}
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. 🙂
Look at your use case, be pragmatic. When in doubt, compare the performance and the complexity of both approaches.