• Hi there,

    i am trying to change the order by function in wordpress to make it order by attributes low to high or high to low (that does not matter). So far i found this on the internet and i am trying to work from there:

    /************* Add sorting by attributes **************/
     
    /**
     *  Defines the criteria for sorting with options defined in the method below
     */
    add_filter('woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args');
     
    function custom_woocommerce_get_catalog_ordering_args( $args ) {
        global $wp_query;
            // Changed the $_SESSION to $_GET
        if (isset($_GET['orderby'])) {
            switch ($_GET['orderby']) :
                case 'pa_nominaal-toerental-omwmin' :
                    $args['order'] = 'ASC';
                    $args['meta_key'] = 'pa_nominaal-toerental-omwmin';
                    $args['orderby'] = 'meta_value_num';
                break;
            endswitch;
        }
        return $args;
    }
    
     
    /**
     *  Adds the sorting options to dropdown list .. The logic/criteria is in the method above
     */
    add_filter('woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby');
     
    function custom_woocommerce_catalog_orderby( $sortby ) {
        $sortby['pa_nominaal-toerental-omwmin'] = 'Sorteer op Toerental: laag naar hoog';
        return $sortby;
    }
    
     
    /**
     *  Save custom attributes as post's meta data as well so that we can use in sorting and searching
     */
    add_action( 'save_post', 'save_woocommerce_attr_to_meta' );
    function save_woocommerce_attr_to_meta( $post_id ) {
            // Get the attribute_names .. For each element get the index and the name of the attribute
            // Then use the index to get the corresponding submitted value from the attribute_values array.
        foreach( $_REQUEST['attribute_names'] as $index => $value ) {
            update_post_meta( $post_id, $value, $_REQUEST['attribute_values'][$index] );
        }
    }
    /************ End of Sorting ***************************/

    The ‘pa_nominaal-toerental-omwmin’ is my attribute i am trying it out with but now if i work with this on the website it randomly filters on something but not sure what.

    Any help here? ??

Viewing 14 replies - 1 through 14 (of 14 total)
  • Thread Starter sjoerd89

    (@sjoerd89)

    Happy new year all,
    still hoping anyone has a solution for this

    Did you save the attributes as metadata first. They won’t be in the wp_postmeta table unless you put them there.

    Thread Starter sjoerd89

    (@sjoerd89)

    How do i know if i did so?

    Attributes aren’t normally saved to the wp_postmeta table, but that’s where they have to be to be available for sorting.

    Adding the attributes to wp_postmeta is achieved by this line towards the end of your code sample:
    update_post_meta(…
    It runs when you save a product. It’ll only work after the code was added into your system, so it will not affect any products that already existed. You would have to add the code, then resave each product to fire the code.

    I’d save a couple of products, then inspect the wp_postmeta table with phpMyAdmin to make sure its working.

    I don’t have a feel for how many products you have. If its a couple of dozen say, you can go through each one and resave it. If you have thousands, you may have to write some more code to loop through all your products to do do the update.

    Sorry, I haven’t tested this, its just what I gather from the code and from here:
    https://stackoverflow.com/questions/37506286/woocommerce-custom-sort-plugin
    “it only recognizes items that have been added or updated since the addition of the code”

    Thread Starter sjoerd89

    (@sjoerd89)

    It is for about 5000 products and with even more attributes to that so manually filling it in like that link from stack will be a very time consuming job. But it might be the way to go. Maybe there is another way but i just can’t seem to find it at the moment.

    You’ll need something like this to loop through your products. It goes in functions.php for your child theme. Uncomment the add_action() to make it run. It may take ages, so comment it again after its done its job. The prints are there so you can see if its finding the right data. Comment them if they are correct. Finally, uncomment the update_post_meta() to actually do the update.

    This has the potential to screw up the wp_postmeta table big style, so back up the table or the database first, or better, run it on a dev install first.

    If you only want certain terms in the wp_postmeta table, you’ll need an if ($name == 'my_term' ) {}in there.

    Its meant as a framework, so some further effort and debugging may be needed.

      // add_action( 'init', 'update_postmeta' );
      function update_postmeta() {
        global $post;
        // get all the products
        $args = array(
         'post_type' => 'product',
         'post_status' => 'publish',
         'numberposts' => -1 ); 
        $selected_posts = get_posts( $args ); // array of 38 posts
    
         // loop through them
        foreach( $selected_posts as $post ) {
          setup_postdata($post); 
          $post_id = get_the_ID();
          print 'Post ID: '.$post_id;
          $object_ids = array( $post_id );
          $taxonomies = array ( 'product_tag' );
          $terms = wp_get_object_terms( $object_ids, $taxonomies );
          if ( !is_wp_error($terms) ) {
            print ' Nr terms found: '.count($terms).'<br>';;
            if ( $terms ) {
              foreach( $terms as $term ) {
                $name = $term->name;
                $slug = $term->slug;
                print 'Name: '.$name.' Slug: '.$slug.'<br>';
                // update_post_meta( $post_id, $name, $slug );
              }
            }
          }
          print '<br>';
          wp_reset_postdata();
        }
      }
    
    Thread Starter sjoerd89

    (@sjoerd89)

    Thanks a lot and i will go and test this out tomorrow will get back to you how this worked out.

    Thread Starter sjoerd89

    (@sjoerd89)

    It does not like this ?? when i tried this it keeps getting errors like this one:
    Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 35 bytes) in /home/zilvertron/domains/zilvertron.com/public_html/wordpress/wp-includes/class-wp-hook.php on line 300

    Thats 128Mb, can you push it to 256Mb or even 512Mb:
    https://docs.woocommerce.com/document/increasing-the-wordpress-memory-limit/

    Otherwise in the args section you would need to fetch the posts so many at a time. The arguments are here:
    https://codex.www.ads-software.com/Class_Reference/WP_Query
    Gets messy, easy to lose track of which ones have been done. I don’t have a feel for how many you can do at a time, some experimentation would be needed. See if it works for one first!

    Thread Starter sjoerd89

    (@sjoerd89)

    Back again :).
    I tried out the code now with increasing my memory limit and it works. But the strange thing is that all my post ID’s come out with
    ‘Post ID: 49474 Nr terms found: 0’

    I am kinda lost now ??

    I tried it before posting. If you’d like to post the whole functions.php on pastebin.com and post just the link here I can take a look.

    Thread Starter sjoerd89

    (@sjoerd89)

    There have been some changes to the lines in the for loop. Its possible one of these changes will be affecting the $post variable.

    My code checker is showing $attribute_values is an unknown variable. Therefore, $taxonomies is also an unknown variable. $product->taxonomies is split over two lines and is being read as just $taxonomies.

    Try running the original code and make sure that works before altering it. As you alter each line, do a print or a var_dump() to make sure the line is behaving as expected.

    Thread Starter sjoerd89

    (@sjoerd89)

    Using the original code will get results like this:

    Post ID: 55449 Nr terms found: 2
    Name: 606.058 Slug: 606-058
    Name: seefrid Slug: seefrid

    It will find the slugs and not taxonomies or attributes. Not totally sure how to edit the code to have it will result in getting that information wich it needs for the filtering.

Viewing 14 replies - 1 through 14 (of 14 total)
  • The topic ‘Changing the orderby’ is closed to new replies.