| @@ -1,0 +1,57 @@ | ||
| 1 | +<?php | |
| 2 | +/** | |
| 3 | + * Ajax Functions | |
| 4 | + * | |
| 5 | + * @package AutomatorWP\WPCode\Ajax_Functions | |
| 6 | + * @since 1.0.0 | |
| 7 | + */ | |
| 8 | +// Exit if accessed directly | |
| 9 | +if( !defined( 'ABSPATH' ) ) exit; | |
| 10 | + | |
| 11 | +/** | |
| 12 | + * Ajax function for selecting snippets | |
| 13 | + * | |
| 14 | + * @since 1.0.0 | |
| 15 | + */ | |
| 16 | +function automatorwp_wpcode_ajax_get_snippets() { | |
| 17 | + // Security check | |
| 18 | + check_ajax_referer( 'automatorwp_admin', 'nonce' ); | |
| 19 | + | |
| 20 | + // Permissions check | |
| 21 | + if( ! current_user_can( automatorwp_get_manager_capability() ) ) { | |
| 22 | + wp_send_json_error( __( 'You\'re not allowed to perform this action.', 'automatorwp' ) ); | |
| 23 | + } | |
| 24 | + | |
| 25 | + global $wpdb; | |
| 26 | + | |
| 27 | + // Pull back the search string | |
| 28 | + $search = isset( $_REQUEST['q'] ) ? $wpdb->esc_like( $_REQUEST['q'] ) : ''; | |
| 29 | + | |
| 30 | + $snippets = automatorwp_wpcode_get_snippets( ); | |
| 31 | + | |
| 32 | + $results = array(); | |
| 33 | + | |
| 34 | + // Parse snippet results to match select2 results | |
| 35 | + foreach ( $snippets as $snippet ) { | |
| 36 | + | |
| 37 | + if( ! empty( $search ) ) { | |
| 38 | + if( strpos( strtolower( $snippet['name'] ), strtolower( $search ) ) === false ) { | |
| 39 | + continue; | |
| 40 | + } | |
| 41 | + } | |
| 42 | + | |
| 43 | + $results[] = array( | |
| 44 | + 'id' => $snippet['id'], | |
| 45 | + 'text' => $snippet['name'] | |
| 46 | + ); | |
| 47 | + } | |
| 48 | + | |
| 49 | + // Prepend option none | |
| 50 | + $results = automatorwp_ajax_parse_extra_options( $results ); | |
| 51 | + | |
| 52 | + // Return our results | |
| 53 | + wp_send_json_success( $results ); | |
| 54 | + die; | |
| 55 | + | |
| 56 | +} | |
| 57 | +add_action( 'wp_ajax_automatorwp_wpcode_get_snippets', 'automatorwp_wpcode_ajax_get_snippets' ); | |