Hướng dẫn wordpress ajax call to functions php - wordpress ajax gọi các hàm php

Tôi có một ứng dụng máy tính để bàn và tôi sử dụng $ .getJson để lấy dữ liệu từ trang web WordPress của tôi bằng plugin API WP REST. Điều này hoạt động tốt và vì vậy tôi cho rằng tôi cũng có thể thực hiện một cuộc gọi Ajax đến một hàm trong các hàm.php? Làm thế nào để tôi làm điều này? Không có ví dụ nào tôi đã thấy cung cấp ajaxurl. Làm thế nào để tôi tìm ra đây là gì?$.getJSON to get data from my wordpress site using the plugin the WP REST API. This works fine and so I assume I can also make an Ajax call to a function in the functions.php? How do I do this? None of the examples I have seen supply the ajaxURL. How do I find out what this is?

Tôi có mã sau:

Function.php (trong trang web WordPress trên máy chủ)

//Called by Ajax from App - list the contents of the folder so they can be downloaded and stored locally
function folder_contents() {

    $folderPath = $_POST['path'] ;
    $files = array_diff(scandir($path), array('.', '..'));
    print_r($files);
    return $files;

    die(); 
}

add_action('wp_ajax_my_action', 'folder_contents');

App.js (chạy bằng nút WebKit cục bộ từ máy)

//ajax call 
var data = {
    action: 'path',
    path: datafolder;
};
var ajaxurl = baseurl + '';  //WHAT IS THIS?!?!
jQuery.post(ajaxurl, data, function(response) {
    alert('Got this from the server: ' + response);
    console.log(response);
});

-------------------EDIT----------------------

Sau câu trả lời bên dưới, tôi đã thử mã dưới đây dựa trên lời khuyên nhưng tôi nhận được

"Index.html: 324 Tham chiếu chưa được thực hiện HERROR: AJAX_PARAMS không được xác định"

Functions.php

//add code to use ajax
function add_ajax_script() {

    wp_localize_script( 'ajax-js', 'ajax_params', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

}

//Called by Ajax from App - list the contents of the folder so they can be downloaded and stored locally

function folder_contents() {

    $folderPath = $_POST['path'] ;
    $files = array_diff(scandir($path), array('.', '..'));
    wp_send_json($files);

    die(); 
}

add_action('wp_ajax_folder_contents', 'folder_contents');
add_action('wp_ajax_nopriv_folder_contents', 'folder_contents');


add_action( 'wp_enqueue_scripts', 'add_ajax_script' );

App.js

//ajax call 
        var data = {action: 'powerpoint_folder_contents',path: datafolder};
        var ajaxurl =  ajax_params.ajax_url;
        console.log(ajaxurl);
        jQuery.post(ajaxurl, data, function(response) {
            alert('Got this from the server: ' + response);
            console.log(response);
        });

Nếu tôi xóa chức năng add_ajax_script () và chỉ cần sử dụng bên dưới, nó sẽ trả về 0.add_ajax_script() function and simply use the below it returns 0.

var ajaxurl = baseUrl + 'wp-admin/admin-ajax.php';

Xin vui lòng giúp đỡ...

Đây có thể là thứ cũ đối với nhiều người ngoài kia và tôi biết rằng hầu hết mọi thứ có thể được thực hiện với API WP tuyệt vời, tôi vẫn nghĩ rằng thật tốt khi có một ví dụ đơn giản về việc sử dụng AJAX để gọi chức năng WordPress trong một bài. Ở đây chúng tôi đi!

Kịch bản: #

Bạn muốn yêu cầu một số dữ liệu từ WordPress (ví dụ: ID bài trước), thông qua cuộc gọi AJAX.

Làm như thế nào: #

Cách tôi giải quyết điều này là thêm một biến toàn cầu trong tiêu đề, để URL AJAX WordPress được phơi bày. Sau đó, tôi đã thêm một chức năng trong tệp chức năng của chủ đề của mình.php, sẽ thực hiện công việc thực tế. Cuối cùng, trong tệp JavaScript của tôi, đó chỉ là vấn đề gọi chức năng của tôi với Ajax. Sau đó tôi có thể sử dụng kết quả để làm những gì tôi cần.


Trong function.php #

function get_prev_ajax_handler() {
  // this is how you get access to the database
  global $wpdb;
  // get the id value which has been posted
  $post_id = intval( $_POST['id'] );
  // Get a global post reference
  global $post;
  // Get the post object for the specified post
  $post = get_post( $post_id );
  // Echo the previous post ID
  echo get_previous_post()->ID;
  // close the connection
  wp_die();
}

add_action('wp_ajax_get_prev', 'get_prev_ajax_handler');
add_action( 'wp_ajax_nopriv_get_prev', 'get_prev_ajax_handler' );

Trong script.js #

function getPrevPostId(id){
  var prevPostId;
  $.post( ajaxUrl, {
      action: "get_prev",
      id: id
    }, function(prevPostId) {
      console.log(prevPostId)
    });
}

Ảnh của Lee Roylland trên unplash

Bạn phải tạo chức năng của bạn trong các chức năng chủ đề của mình.php Đây là ví dụ cho tải các bài viết phổ biến bằng cách sử dụng Ajax

function getPopularPosts()
{
    $popularpostdata = wpp_get_mostpopular_data();
    foreach($popularpostdata as $populardata)
        {
            $cur_id = $populardata->id;
            $cur_date = $populardata->post_date;
            $cur_date = date("F j, Y", strtotime($cur_date));
    ?>
    
>

'.getCategoryLink().''; $post_mp = get_post($cur_id); ?>

title;?>

post_author,$cur_id,$populardata->title,$cur_date); ?>
postcontent; //$content_post->post_content; $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); echo $content; wp_link_pages( array( 'before' => '', 'link_before' => '', 'link_after' => '', 'pagelink' => '' . __( 'Page', 'twentyfifteen' ) . ' %', 'separator' => ', ', ) ); ?>

TAGS:

post_author,$cur_id,$populardata->title); ?>
', '' ); ?>
Hướng dẫn wordpress ajax call to functions php - wordpress ajax gọi các hàm php

'); $.ajax({ type: 'POST', url: "/wp-admin/admin-ajax.php", data: { action: 'getPopularPosts' }, success: function( data ) { $('.popularposts').html(data); } }); } });

Làm thế nào để thực hiện cuộc gọi Ajax trong WordPress?

Khi bạn sẽ thực hiện một cuộc gọi AJAX, bạn sẽ cần gửi yêu cầu đến tệp admin-ajax.php, đây là một phần của WordPress Core. Tệp này chịu trách nhiệm xử lý và xử lý tất cả các yêu cầu AJAX của bạn trong bối cảnh WordPress. Không sử dụng URL trực tiếp của đường dẫn tệp.send the request to the admin-ajax. php file, which is a part of WordPress core. This file is responsible for handling and processing all of your Ajax requests within the WordPress context. Do NOT use the direct URL of the file path.

Bạn có thể sử dụng AJAX với PHP không?

Bắt đầu sử dụng AJAX ngay hôm nay trong hướng dẫn PHP của chúng tôi, chúng tôi sẽ chứng minh cách AJAX có thể cập nhật các phần của trang web, mà không cần tải lại toàn bộ trang.Tập lệnh máy chủ sẽ được viết bằng PHP.Nếu bạn muốn tìm hiểu thêm về Ajax, hãy truy cập hướng dẫn Ajax của chúng tôi.The server script will be written in PHP. If you want to learn more about AJAX, visit our AJAX tutorial.

Quản trị viên ở đâu

Theo mặc định, WordPress chỉ đạo tất cả các cuộc gọi AJAX thông qua Quản trị viên-AJAX.Tệp PHP nằm trong thư mục WP-Admin của Trang web./wp-admin directory.

Làm cách nào để nhận dữ liệu AJAX trong WordPress?

Trong WordPress, chúng tôi gửi tất cả yêu cầu AJAX đến một URL chung, sau đó WordPress gọi phương thức tương ứng theo các tham số mà chúng tôi đã gửi với yêu cầu.Bạn có thể sử dụng chức năng admin_url ('admin-ajax.php') của WordPress để lấy URL này.use the admin_url( 'admin-ajax. php' ) function of WordPress to get this url.