0

i use this function to get all products of one category in ajax request

function get_products()
 {
   $cat_id = $_POST['category'];
   $args = array(
  'post_type'             => 'product',
  'post_status'           => 'publish',
  'ignore_sticky_posts'   => 1,
  'posts_per_page'        => '12',
  'tax_query'             => array(
    array(
        'taxonomy'      => 'product_cat',
        'field' => 'term_id', //This is optional, as it defaults to 'term_id'
        'terms'         => $cat_id,
        'operator'      => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
    ),
    array(
        'taxonomy'      => 'product_visibility',
        'field'         => 'slug',
        'terms'         => 'exclude-from-catalog', // Possibly 'exclude-from-search' too
        'operator'      => 'NOT IN'
    )
 )
);
 $products = new WP_Query($args);
 echo json_encode($products);

 wp_die();
}

then i received data of each product but not all data of each product

ID: 75
post_author: "4"
post_date: "2020-04-21 08:45:26"
post_date_gmt: "2020-04-21 08:45:26"
post_content: "samsung galaxy is very attractive mobile"
post_title: "samsung galaxy"
post_excerpt: "this samsung galaxy vvvvvvvvvvvv"
post_status: "publish"
comment_status: "open" 
ping_status: "closed"
post_password: ""
post_name: "samsung-galaxy"
to_ping: ""
pinged: ""
post_modified: "2020-04-29 12:06:42"
post_modified_gmt: "2020-04-29 12:06:42"
post_content_filtered: ""
post_parent: 0
guid: "http:
menu_order: 0
post_type: "product"
post_mime_type: ""
comment_count: "1"
filter: "raw"

i can't find image or product price or sale price or rate

i want to get this data in the script

function get_div(obj)
{
console.log("heeeeeeeeeeeeeeeere");
console.log(obj.ID);
console.log(obj.post_name);
console.log(obj.regular_price);=> return undefined
}          

what is the proplem???

0

For instance, WP_Query is only for fetching standard post data. Additional data by plugins such as WC will not be fetched.

To do a custom query

If you would like to use a custom query, you could use WC_Product_Query

Place the following in theme's functions.php and save the javascript into a separate php file. The quick test used WC default sample products.

// in theme's functions.php
// before init, no products is prepared if just direct call in functions.php, so to have quick test, need to place inside a init
add_action( 'init', 'ws365398_simple_test' );
function ws365398_simple_test() {
    add_action('wp_enqueue_scripts', 'ws365398_enqueue_scripts', 101);

    add_action( 'wp_ajax_my_action', 'get_products' );
    add_action( 'wp_ajax_nopriv_my_action', 'get_products' );
}

// actions for ajax
function get_products()
{
    if( !empty( $_POST['category'] ) ) {
        $cat_id = $_POST['category'];
    } else {
        $cat_id = 19; // default change to yours, in the test case ensure it have something by default
    }

    $args = array(
        'status'           => 'publish',
        'ignore_sticky_posts'   => 1,
        'posts_per_page'        => '12',
        'tax_query'             => array(
            'relation'          => 'AND', // relation of 2 taxonomy queries
            array(
                'taxonomy'      => 'product_cat',
                'field'         => 'term_id', //This is optional, as it defaults to 'term_id'
                'terms'         => $cat_id,
                'operator'      => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
            ),
            array(
                'taxonomy'      => 'product_visibility',
                'field'         => 'slug',
                'terms'         => 'exclude-from-catalog', // Possibly 'exclude-from-search' too
                'operator'      => 'NOT IN'
            )
        )
    );
    $query = new WC_Product_Query($args);
    $products = $query->get_products();

    // convert to array data before pushing to json
    $product_arr = [];
    foreach ($products as $key => $product) {
        $product_arr[] = $product->get_data();
    }

    // echo json_encode($product_arr);
    wp_send_json_success( $product_arr ); // with success flag and use directly

    wp_die();
}

// enqueue ajax script
function ws365398_enqueue_scripts()
{
    wp_enqueue_script('test-custom-scripts', get_theme_file_uri('ws365398-test-ajax.php'), array(), 't' . time(), true);
}
<?php

// ws365398-test-ajax.php
/** Load WordPress Bootstrap */
// change to your path
require_once( '/project/wp-load.php' );

header("Content-type: text/javascript");?>

function test_ajax() {
    let myData = {
      action: 'my_action',
    };

    jQuery.post('<?php echo admin_url( 'admin-ajax.php' );?>', myData, function (response) {

      if (response.success == true) {
        console.log(response);
        }
    });
}

To test, just prepare the above files with corrected path for your environment. Run test_ajax() in browser inspector and you will see something like the following:

enter image description here

| improve this answer | |
  • i get the data of the product in script not in single product page – Omnia Magd Apr 29 at 14:45
  • I have just updated the answer for your function, you could use WC_Product_Query to query products. I have just tried and it should work the way you expect – simongcc Apr 29 at 14:50
  • can't work it make error in script in Uncaught TypeError: Cannot read property 'length' of undefined – Omnia Magd Apr 29 at 15:03
  • Which variable is wrong in the error message? Since I have updated twice, the first copy & paste was wrong and I have fixed it immediately. the first update was // $cat_id = $_POST['category']; which is wrong, it should be $cat_id = $_POST['category']; Is this the error message you have seen? And your $_POST['category'] is getting from a form, right? If it is not passing from a form, it will be undefined. I suggest you add a checking, the example code is updated – simongcc Apr 29 at 15:08
  • @OmniaMagd I have updated your function, to get_product, need to use the query method instead and I have added comments to some of the arguments. – simongcc Apr 29 at 15:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.