簡體   English   中英

如何在 Wordpress 中從 jQuery 調用 php 函數

[英]How to call the php function from the jQuery in Wordpress

我在我的頁面和 onChange 事件上顯示類別下拉列表,我必須調用latestBlogView()函數。

我的所有代碼都在 function.php 頁面中。

  1. 我需要使用 AJAX 嗎?
  2. 可以不用 AJAX 嗎?

我必須調用這個函數

function latestBlogView($atts){
    var_dump($atts);
    $postData=$atts; // this code is for testing i have to use WP_Query here
    return $postData; 
}
add_shortcode( 'latestblogs', 'latestBlogView');

在我的頁面上顯示 dropdonw

function categoriesDropdown(){
$categories = get_categories( array(
    'orderby' => 'name',
    'order'   => 'ASC',
    'taxonomy' => 'blogs_cat',
) );
 $output='';
 $output.='<select name="catDropdown" id="catDropdown">';
foreach( $categories as $category ) {
    $output.='<option value="'.$category->term_id.'">'.$category->name.'</option>'; 
}
    $output.='</select>';
    $output.='<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" crossorigin="anonymous"></script><script>(function($){$("#catDropdown").change(function() {
    var value=$("#catDropdown").val();
    latestBlogView(value); // calling function here
    });
    })(jQuery)</script>';
    return $output;
}
add_shortcode( 'showCategoryList', 'categoriesDropdown');

我嘗試使用 ajax 並且它正在工作。 我不知道這是否是最好的方法,但它解決了我的問題。

我使用的是jquery-3.5.1.slim.min.js所以我改變了它,因為我在控制台中收到錯誤$.ajax is not a function

我試過下面的ajax代碼

$output.='<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" crossorigin="anonymous"></script><script>     
(function($) {  // ready handler
$("#catDropdown").change(function() {
     $.ajax({
        url: "/wp-admin/admin-ajax.php",
        type: "post",
        data: { action: "latestBlogView", keyword: $("#catDropdown").val() },
        success: function(data) {
            $("#latestblogs").html(data);
        }
    });
    });
    })(jQuery);</script>';

這是我的功能

add_action('wp_ajax_nopriv_latestBlogView', 'latestBlogView');
add_action('wp_ajax_latestBlogView', 'latestBlogView');

function latestBlogView($atts){
echo "hello"; // if you want to display the variable output on screen then use return $postData; 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM