Quiero configurar una url ajax para usarla con Datatables en wordpress. Pero no sé cómo configuraría la URL correspondiente en wordpress. Supongo que es una tarea bastante fácil, pero no sé cómo hacerlo.
Encontré un código de ejemplo sobre cómo configurar el procesamiento del lado del servidor de tablas de datos en wordpress, pero tengo dificultades para poner el siguiente código en la vida real (¿cómo crear el FrontendConfig.ajaxurl correspondiente en Wordpress? ¿O sería mejor crear un punto final json de wordpress? )
jQuery
jQuery('#student_table').DataTable({ "bProcessing": true, "serverSide": true, "ajax":{ "url": FrontendConfig.ajaxurl+'?action=getStudentsFromExamIdAjax&exam_nounce=exam_nounce_data&exam_id=1', type: "post", } });wordpress php
add_action('wp_ajax_getStudentsFromExamIdAjax', 'getStudentsFromExamIdAjax' ); add_action('wp_ajax_nopriv_getStudentsFromExamIdAjax', 'getStudentsFromExamIdAjax' ); function getStudentsFromExamIdAjax(){ if(empty($_GET['action']) || empty($_GET['exam_id'])){ wp_send_json_error( new \WP_Error( 'Bad Request' ) ); } if(isset($_GET['exam_id']) && $_SERVER['REQUEST_METHOD'] === 'POST' && wp_verify_nonce( $_GET['exam_nounce'], 'exam_nounce_data' )): $exam_id = (isset($_GET['exam_id'])) ? absint($_GET['exam_id']) : ''; /*@ You can create a function to get the data here */ $students = getStudentsFromExamId($exam_id); $tdata = []; foreach ($students as $key => $value): $tdata[$key][] = $value->roll_no; $tdata[$key][] = $value->name; $tdata[$key][] = $value->phone; $tdata[$key][] = 'action here'; endforeach; $total_records = count($tdata); $json_data = array( /* $_REQUEST['draw'] comes from the datatable, you can print to ensure that */ "draw" => intval( $_REQUEST['draw'] ), "recordsTotal" => intval( $total_records ), "recordsFiltered" => intval( $total_records ), "data" => $tdata ); echo json_encode($json_data); endif; wp_die(); }Solo necesita configurar los siguientes enqueue_style_and_scripts en su archivo function.php . Debe configurar wp_localize_script , consulte este enlace https://developer.wordpress.org/reference/functions/wp_localize_script/ . No olvide cambiar el código según sus requisitos de codificación.
/*@ Enqueue styles & scripts */ if( !function_exists('enqueue_style_and_scripts') ): function enqueue_style_and_scripts(){ $version = wp_get_theme()->get('Version'); wp_enqueue_script( 'general_js', get_stylesheet_directory_uri() . '/assets/js/general.js', array('jquery'), $version, true ); $frontendconfig = array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'is_user_logged_in' => is_user_logged_in(), ); wp_localize_script( 'general_js', 'FrontendConfig', $frontendconfig ); } add_action('wp_enqueue_scripts', 'enqueue_style_and_scripts'); endif;