• Hi, I have a custom post type to show some products.
    I need to sort those products on the archive index page by name.
    However I need to exclude a word “XYZ” from the ordering:

    Product names are as follows and in the order they should appear:

    XYZ Product a
    XYZ Product b
    Product c

    Is there a way to do omit “XYZ” from the name ordering in the post query?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter lokust

    (@lokust)

    In case it helps someone else:

    This was the solution, in functions.php

    add_filter('posts_orderby_request', 'my_posts_orderby_request', 10, 2);
    function my_posts_orderby_request($orderby, $query) {
        if ($query->get('clean_xyz')) {
            return "REPLACE(LOWER(post_title), 'xyz ', '') ASC";
        }
        return $orderby;
    }
    
    add_action( 'pre_get_posts', 'my_pre_get_posts' );
    function my_pre_get_posts($query) {
        if ($query->is_post_type_archive('product') && $query->is_main_query() && $query->get('post_type') == 'product' && !$query->get('orderby')) {
            $query->set('clean_xyz', true);
        }
    }

    maybe to help other perssones ??

    $value= 'YOUR QUERY TAXONOMY';
    $replace = str_replace('XYZ' ,'',$value);
    echo $replace ;

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Custom post query’ is closed to new replies.