wordpress change the loop order by dynamic value

At the moment i have a custom field named “price” to order my posts correctly.

The following already works:

Read More
  $query_args['meta_key'] = 'price';
  $query_args['orderby'] = 'meta_value_num';
  $query_args['order'] = 'asc';

The problem is that this is a “recommended” price, the real price needs to be calculated inside the loop.

The question is to know if there is a way or a trick, where we can run the loop, calculate the real price and show the posts based on the real price variable.

Related posts

Leave a Reply

1 comment

  1. At the moment you publish/update the post with recommended price, it’s better to have another custom meta post to save the real price in it by using add_action() and add_post_meta(), then you can use the query you posted but with $query_args['meta_key'] = 'real_price';

    Something like below:

    function wp_po54785( $post_id )
    {
        $recommended_price = get_post_meta( $post_id, 'price', true );
        if ( ! $recommended_price )
            return;
    
        // Avoid infinite loops
        remove_action( current_filter(), __FUNCTION__ );
        // If you're doing this from inside a class:
        # remove_action( current_filter(), array( $this, __FUNCTION__ ) );
    
        // The Algorithm
        // You use to
        // Calculate real price
        // By doing works on $recommended_price
        // And put in $real_price;
        add_post_meta( $post_id, 'real_price', $real_price );
    }
    add_action( 'save_post', 'wp_po54785' );