diff --git a/README.md b/README.md index b6e8085..963b0d1 100644 --- a/README.md +++ b/README.md @@ -130,6 +130,30 @@ $instance->doSomething(); ``` +### AjaxTrait + +The `AjaxTrait` provides a function to create the WordPress AJAX actions easily. No need to add actions for logged-in and logged-out users separately. + +Usage example: + +```php +use WeDevs\WpUtils\AjaxTrait; + +class MyAjaxClass { + + use AjaxTrait; + + public function __construct() { + // Register an AJAX action. + // This will produce: + // add_action( 'wp_ajax_yourproject_submit_form, [ $this, 'submit_form_callback' ] ); + // add_action( 'wp_ajax_nopriv_yourproject_submit_form, [ $this, 'submit_form_callback' ] ); + $this->register_ajax( 'yourproject_submit_form', [ $this, 'submit_form_callback' ] ); + } +} + +``` + ## License diff --git a/src/AjaxTrait.php b/src/AjaxTrait.php new file mode 100644 index 0000000..5ac9caa --- /dev/null +++ b/src/AjaxTrait.php @@ -0,0 +1,53 @@ + false ]; + + /** + * A predefined array to use when we need to create AJAX actions only for logged out users + * + * @var array + */ + protected $logged_out_only = [ 'nopriv' => true, 'priv' => false ]; + + /** + * Register ajax into action hook + * + * Usage: + * register_ajax( 'action', 'action_callback' ); // for logged-in and logged-out users + * register_ajax( 'action', 'action_callback', [ 'nopriv' => false ] ); // for logged-in users only + * register_ajax( 'action', 'action_callback', [ 'nopriv' => true, 'priv' => false ] ); // for logged-out users only + * + * @param string $action + * @param callable|string $callback + * @param array $args + * + * @return void + */ + public function register_ajax( $action, $callback, $args = [] ) { + $default = [ + 'nopriv' => true, + 'priv' => true, + 'priority' => 10, + 'accepted_args' => 1, + ]; + + $args = wp_parse_args( $default, $args ); + + if ( $args['priv'] ) { + add_action( 'wp_ajax_' . $action, $callback, $args['priority'], $args['accepted_args'] ); + } + + if ( $args['nopriv'] ) { + add_action( 'wp_ajax_nopriv_' . $action, $callback, $args['priority'], $args['accepted_args'] ); + } + } +}