woocommerce product sorting based on custom fields

Question

I am trying to add a custom sorting option for woo commerce . So I am using following code to add new sort option plus set it as default

meta key is ‘_am_cat_sort’

function sv_personagem_woocommerce_shop_ordering( $sort_args ) {
  $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );

    if ( 'personagem' == $orderby_value ) {
        $sort_args['orderby'] = '_am_cat_sort';
        $sort_args['order'] = 'ASC';
        $sort_args['meta_key'] = '';
    }

    return $sort_args;
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'sv_personagem_woocommerce_shop_ordering' );

function sv_custom_woocommerce_catalog_orderby( $sortby ) {
    $sortby['personagem'] = 'Sort by cat: personagem';
    return $sortby;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'sv_custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'sv_custom_woocommerce_catalog_orderby' );

add_filter('woocommerce_default_catalog_orderby', 'custom_default_catalog_orderby');

function custom_default_catalog_orderby() {
     return 'personagem'; // Can also use title and price
}

Now following is the code I am using to add new meta field

add_action('add_meta_boxes', 'add_am_product_metaboxes');

function add_am_product_metaboxes() {
add_meta_box('wpt_am_product', __('Sort value'), 'wpt_am_product', 'product', 'normal', 'high', null);
}

function wpt_am_product(){
  // Add the HTML for the post meta
  global $post;
  // Noncename needed to verify where the data originated
  wp_nonce_field( 'oj-am_product-fields', 'oj-am_product-fields_wpnonce', false, true );
  // Get the location data if its already been entered 

  $am_cat_sort  = get_post_meta($post->ID,  '_am_cat_sort', true);
  $am_cat_sort  = (int)$am_cat_sort; 
  $terms = wp_get_post_terms( $post->ID, 'product_cat' );
  $myterms=array();
  foreach ($terms as $term) {
    $myterms[]=$term->term_id;
   } 
  if(in_array(76, $myterms)){
    $am_cat_sort  = -99;
  }else{
    $am_cat_sort  = 0;
  }

  echo '<label >';?><?php _e( 'sort order' );?></label> 
  <?php echo '<br><textarea  name="_am_cat_sort" rows="4" cols="80">'.$am_cat_sort.'</textarea>'.'<br>'; 

}

But sorting is not working at all

Thanks in advance

0
, , , user7459842 4 years 2020-05-29T21:10:44-05:00 0 Answers 102 views 0

Leave an answer

Browse
Browse