使用ajax从wordpress数据库中获取产品

时间:2017-10-08 13:43:24

标签: php jquery ajax wordpress

我正在使用WordPress构建自定义产品页面(page1.php)。

我在自定义产品页面(page1.php)上使用Ajax,调用包含下面代码(page2.php)的其他页面,使用下面的代码从wordpress数据库中获取产品。

@Override
public void onBindViewHolder(ActiveViewHolder viewHolder, int pos) {
    Subscription sub = activeSubsList.get(pos);
    viewHolder.title.setText(sub.getTitle());
    viewHolder.cycle.setText(cycleArray[sub.getCycle()]);
    viewHolder.duration.setText(durationArray[sub.getDuration()]);
    viewHolder.price.setText(String.valueOf(sub.getPrice()).concat(currency.getSymbol()));
    viewHolder.firstBill.setText(sub.getFirstPayment());
    viewHolder.relativeLayout.setBackgroundColor(mContext.getResources()
                .getColor(sub.getColor()));
    viewHolder.expandableLayout.setBackgroundColor(mContext.getResources()
                .getColor(sub.getColor()));
    Picasso.with(mContext).load(sub.getImage()).into(viewHolder.image);
}

上面的代码实际上工作正常我没有通过AJAX调用它(即直接从www.localhost / wordpress / page2.php加载它),但是当我通过page1.php上的ajax调用它时,我得到以下错误;

致命错误:未捕获错误:类' WP_Query '在C:\ xampp \ htdocs \ wordpress-fully-custom \ wp-content \ themes \ storefront \ page2.php中找不到:9堆栈跟踪:#0 {main}抛出C:\ xampp \ htdocs \ wordpress-fully-第9行的custom \ wp-content \ themes \ storefront \ test-page2.php

我该如何解决这个问题?

由于

3 个答案:

答案 0 :(得分:2)

在这里,我已经尝试过我的主题并且工作得很好!

希望这对你有用。

AJAX CALL的Scipt代码:

jQuery('#productDataSubmit').click(wc_load_all_products);
    function wc_load_all_orders() {
        jQuery("#wc-products").html("");

        jQuery.ajax({
            type: "POST",
            url: ajax_details.ajax_url,
            data: {action: 'get_wc_products'},
            success: function (data) {
                var products = jQuery.parseJSON(data);
                jQuery('#wc-products').html(products.product_html);
            }
        });
        return false;
    }

为返回产品调用AJAX函数的操作(将其添加到functions.php中)

    add_action('wp_ajax_get_refund_data', 'get_wc_products');
    add_action('wp_ajax_nopriv_get_refund_data','get_wc_products');

获取产品的功能(将其添加到functions.php中)

     /**
     * AJAX function for products.
     */
    function get_wc_products() {
    $html="";
    $varition_args = array(
            'post_type' => 'product',
            'posts_per_page' => 10,
            'product_cat'    => 'bags'
        );
        $variation_query = new WP_Query($varition_args);
    }


    if ($variation_query->have_posts()) {
            while ($variation_query->have_posts()) {
                 $variation_query->the_post();
                 global $product;
                 $html.= '<tr>';
                 $html.= '<td>'.get_the_ID().'</td>';
                 $html.= '<td>'.get_the_title().'</td>';
                 $html.= '<td>'.$product->get_price_html().'</td>';
                 $html.= '</tr>';
            }
    }

    //Returns records
    $data = [];
    $data['product_html'] = $html;
    }

答案 1 :(得分:0)

当您直接查看该页面时,WP_Query类会以某种方式导入。由于这不是通过AJAX发生的,因此您可能希望在该页面上明确包含它。可以这样做:

include_once "path/to/wp-includes/class-wp-query.php";

答案 2 :(得分:0)

有很多关于wordpress ajax的教程。你最好看看这些东西......

Wordpress Official Ajax Tutorial

Sitepoint Ajax Tutorial With Some Good Examples

Code Tuts Tutorial For Frontend Ajax

Smashing Magazine Ajax Tutorial

现在让我们在这里给你一个快速的ajax示例:

jQuery(document).ready(function(){
   jQuery(".ajax_button_to_click").click(function(event){
    // event.preventDefault(); enable this if you want to stop click 
   behavior
    var ajax_form_input_value = jQuery('#ajax_input_value').val();
    var ajax_text = jQuery('#ajax_text_value').text();
    jQuery.ajax({
       method: "POST", // http request method
       url: ajaxurl, // indicates wp-ajax.php file which will handle the request
       data: {'action':'ajax_function_name', //function name which will handle the ajax request inside your plugin or theme's functions.php file
              'ajax_text_data':ajax_text, //text data to send with the ajax request
              'ajax_form_value: ajax_form_input_value ' }, //form input data to send with the ajax request
       success:function(data) { //on ajax request success run all inside this method
        alert(data); 
    },
    error: function(errorThrown){ //if ajax fails then run this method
        console.log(errorThrown);
      }
    });
  });
});

现在是后端的ajax请求处理部分。

首先添加Js ajaxurl var:

add_action('wp_head', 'prefix_ajaxurl');

 function prefix_ajaxurl() {
   echo '<script type="text/javascript">
        var ajaxurl = "' . admin_url('admin-ajax.php') . '";
     </script>';
 }

第二次添加Ajax Action函数

function ajax_function_name(){ // function name should be same defined in ajax request action var.
     $text = $_POST['ajax_text_data'];
     $input_data = $_POST['ajax_form_value'];
     echo $text;
     echo $input_data;
     die(); //you must write die(); to avoid echoing extra 0;
 } 
 add_action( 'wp_ajax_ajax_function_name', 'ajax_function_name' ); ?>