Are you a GenerateCustomer?

Do you have an active GP Premium or GenerateBlocks Pro license key?

Create a GenerateSupport account for GeneratePress and GenerateBlocks support in one dedicated place.

Create an account
Already have a GenerateSupport account? Login

Just browsing?

Feel free to browse the forums. Support for our free versions is provided on WordPress.org (GeneratePress, GenerateBlocks).

Want to become a premium user? Learn more below.

Query by custom taxonomy and sorting by post meta

  • I have created a custom taxonomy using ACF. Now I am trying to customize the archive page associated with the custom taxonomy. I am using the new Query block and have been able to set the search parameters appropriately. But now I am trying to order the results using a post meta field. And I am stuck there. Any help, or a reference to the correct documentation, would be greatly appreciated (I have looked but found nothing so far). Thanks.

  • Hi there,

    GB does not have an order by post meta option; you will need to use custom PHP code for the query.

    What field type is the post meta? Date or number?

    Let me know 🙂

  • It is a number, an integer.

  • Hi there,

    First, select the Query block and add the class order-by-post-meta under Advanced > Additional CSS Classes.

    Then add this snippet to your site:

    
    add_filter('generateblocks_query_wp_query_args', function ($args, $attributes, $block, $current) {
        if (empty($attributes['className']) || strpos($attributes['className'], 'order-by-post-meta') === false) {
            return $args;
        }
    
        // Order by the meta value (descending = latest/highest first)
        $args['meta_key'] = 'your_meta_key_name'; // Replace with your meta key
        $args['orderby']  = 'meta_value_num';     // Use meta_value_num for integers
        $args['order']    = 'DESC';               // DESC for highest first, ASC for lowest first
    
        return $args;
    }, 10, 4);
    

    Adding PHP: https://docs.generatepress.com/article/adding-php/

    Make sure to replace your_meta_key_name with the actual meta key you want to order by.

    This will order the Query block items based on the meta value you specify.

  • That did the trick. Thanks a bunch.

  • You’re welcome!

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.