0

Working on Wordpress / Woocommerce architecture, I'm new in woocommerce, before i've worked on django and laravel framework, the project is a plugin wp, where a little form is fit with select tags for give me back some products by their sku. I can get the products objects, but I can't override the wp_query returned by the ajax response and, at the same time override the archive loop template with my custom datas and display my final result.

Here is my class :

    if(!defined('EXCELREADER_ASSETS_URL'))
    define('EXCELREADER_ASSETS_URL', dirname(  FILE ));

class GetAllMenu {

public $tab;

public $id_product;

public function __construct(){
    add_action( 'search-phone', array( $this, 'render_phone_search' ) );
    add_action( 'wp_enqueue_scripts', array( $this, 'init_plugin' ) );
    add_action('wp_ajax_render_phone_search', array($this,'render_phone_search'));         
    add_action('wp_ajax_nopriv_render_phone_search', array($this,'render_phone_search')); 

    add_action( 'search-phone', array( $this, 'display_search_result' ) );
    add_action('wp_ajax_display_search_result', array($this,'display_search_result'));         
    add_action('wp_ajax_nopriv_display_search_result', array($this,'display_search_result')); 
}

public function init_plugin()
{
    wp_enqueue_script( 
        'ajax_script', 
        plugins_url( 'assets/js/admin.js', EXCELREADER_ASSETS_URL ), 
        array('jquery'), 
        TRUE 
    );
    wp_localize_script( 
        'ajax_script', 
        'searchAjax', 
        array(
            'url'   => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce( "search-phone" ),
        )
    );
}

public function render_phone_search(){
    $id = urldecode($_POST['phone_id']);
   if(isset($id)){
        $objPhone = new ER_PhoneName();
        $phone = $objPhone->get_phones_by_mark(trim($id));
        include(EXCELREADER_TEMPLATE_URL . '/search-phone-widget.php');
   }
    exit;
}

public function render_mark_search(){
    $mark = new ER_PhoneMark();
    $data = $mark->call_all_mark_in_db();
    include(EXCELREADER_TEMPLATE_URL . '/search-widget.php');
}

public function display_search_result(){
    $sku = urldecode($_POST['sku_universel']);
    $sku = explode(',',$sku);
    $this->tab = array();
    foreach($sku as $res){
        $product =  PhpSpreadReader::select_product_by_sku($res);
        if($product){
            $this->id_product[] = $product->get_id(); 
            $this->tab[] = $product;          
        }
    }
    $args = array(
        'post_type' => array('products'),
        'post_status' => array('publish'),
        'post__in' => $this->id_product
    );

    // The Query here is my problem =====================================
    $ajaxposts = new WP_Query( $args );

    $response = '';

    // The Query i want to use my archive product in my theme not this one
    if ( $ajaxposts->have_posts() ) {
        while ( $ajaxposts->have_posts() ) {
            $ajaxposts->the_post();
            $response .= get_template_part('woocommerce/content-product');
        }
    } else {
        $response .= get_template_part('none');
    }

    echo $response;

    //echo get_language_attributes();
    //echo $this->display_product_result();
exit;
}

public function changing_query_post($wp_query){
    $wp_query->posts;
    if ( $wp_query->is_home() && $wp_query->is_main_query() ) {
        $wp_query->set( 'post__in', array($this->tab) );
    }
    return $wp_query;
}


public function render_search(){
    $this->render_mark_search();
}

}

Here is my ajax call in js :

$(document).on("click", "#ex-form-submit", (e) => { e.preventDefault() if($("#option-mark").val() === "0"){ return; } let str = { 'action': 'display_search_result', 'sku_universel': $("#select-phone").val(), }; // console.log(searchAjax.url); $.ajax({ type : "post", dataType : "html", url : searchAjax.url, data : str, success: (response) => { $('.grilleproduits').html(response).resize(); console.log(response); }, error : (error) => console.log(error) }); });

I can display all in js but it's not a right way to do this, cause some problems like the product title translation don't follow when the result is displayed.

Thanks in advance for any support and sorry for my nooby skills ! I answer only during week cause i don't have the code and website for my test in week end.

edit : I forgot to say it's a plugin that i'm developing

  • My reading comprehesion isn't collaboration at the moment. Is it that you want to get different results from WP_Query or change the html that the php sends back to the jQuery? – Antti Koskinen Feb 15 at 18:54
  • Hi @AnttiKoskinen, thx for your answer. I want to change the WP_Query post data with my products chosen by their id, for display them in my loop located at "mytheme/woocommerce/archive-product.php". Is it possible to display that with my AJAX response ? – Oliver Feb 15 at 19:47
0

Yes, you can query products by their ids and display them as ajax response. You code just needs a little revision. Perhaps you could try something along these lines,

public function display_search_result(){ 

  $skus = urldecode($_POST['sku_universel']); 
  $skus = explode(',',$sku);
  $product_ids = array();

  // you can use native woocommerce function to get the product ids
  foreach($skus as $sku){
    $product_id = wc_get_product_id_by_sku($sku);
    if ( is_int($product_id) ) { 
      $product_ids[] => $product_id;
    }
  } 

  $args = array( 
    'post_type'      => 'product', // product, not products
    'post_status'    => 'publish', 
    'post__in'       => $product_ids,
    'posts_per_page' => 100 // change this based on your needs
  );
  $ajaxposts = new WP_Query( $args );

  $response = '';

  if ( $ajaxposts->posts ){ 
    while ( $ajaxposts->have_posts() ) { 
      $ajaxposts->the_post(); 
      $response .= wc_get_template_part( 'content', 'product' ); // use WooCommerce function to get html
    } 
  } else { 
    // handle not found by yourself or
    // perhaps do_action( 'woocommerce_no_products_found' ); could do the trick?
  }

  echo $response;
  exit;

}
  • I don't even know there is a wc_get_product_id_by_sku despite of all my research, alright for this. But I can't call my template stocked at my mytheme/woocommerce/archive-product.php (the loop template) with my custom query, cause has I update after my question it's a plugin that i'm developing.... – Oliver Feb 16 at 8:53
  • Sorry, my bad. I updated the code example. You can use WC native wc_get_template_part function to get the required template part. – Antti Koskinen Feb 16 at 8:58
  • I try that monday thx you very much man. I update my code if this work. – Oliver Feb 16 at 20:39
  • I followed your indication, it display a result but i think I should reset the wp_query cause old products are always displayed ! And the pagination don't update ! – Oliver Feb 18 at 8:14
  • If you want to replace previous products with the newly queried ones on the front end, then you'll need to use js/jquery to remove the old ones first. Perhaps you could alter the ajax response to be an array including the product html and some pagination data (maybe get this from WP_Query?). Then use js/jquery to modify pagination on the front end. – Antti Koskinen Feb 18 at 13:47
0

Alright first of all,Thank you for your help ! Your wc_get_product_id_by_sku was not working (return null all the times) so i keep my last function, i can display with my custom query and good style just a last question my nav menu search is displayed 2 times ! I think i need to do a remove action ?

   public function display_search_result(){
    $sku = urldecode($_POST['sku_universel']);
    $sku = explode(',',$sku);
    $this->tab = array();
    foreach($sku as $res){
        $product =  PhpSpreadReader::select_product_by_sku($res);
        if($product){
            $this->id_product[] = $product->get_id();       
        }
    }
    $args = array( 
        'post_type'      => 'product', // product, not products
        'post_status'    => 'publish', 
        'post__in'       => $this->id_product,
        'posts_per_page' => 100, // change this based on your needs
        'page' => '1'
      );
    // The Query
    $ajaxposts = new WP_Query( $args );

    $response = '';

    // The Query
    $response .= woocommerce_product_loop_start();

    if ( $ajaxposts->have_posts() ) {
        while ( $ajaxposts->have_posts() ) {
            $ajaxposts->the_post();
            $response .= wc_get_template_part( 'content', 'product' );
        }
    } else {
        $response .= get_template_part('none');
    }

    $response .= woocommerce_product_loop_end();

    //$response .= get_template_part('/woocommerce/theme-custom/woo', 'pagination'); 

    echo $response;

    //echo get_language_attributes();
    //echo $this->display_product_result();
exit;
}

And my pagination still doesn't work I continue my search...

  • I've notice when I reload the page, ajax is not working anymore too... – Oliver Feb 18 at 13:31

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.