Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance/ajax trait #1

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
53 changes: 53 additions & 0 deletions src/AjaxTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

namespace WeDevs\WpUtils;

trait AjaxTrait {

/**
* A predefined array to use when we need to create AJAX actions only for logged in users
*
* @var array
*/
protected $logged_in_only = [ 'nopriv' => 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'] );
}
}
}