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.

Order Query Loop By Custom Field

  • Hi team,

    I followed this guide: https://docs.generateblocks.com/article/order-query-loop-by-custom-field but for some reason, it won’t work.

    Maybe because in my case, I’ve added the custom field on each page but the value of that custom field is not on the loop?

    Also, below is my query loop:

    Query Loop

    My setup is quite different, I used shortcode and render_block, please check below the codes:

    Shortcode PHP:

    function make_star_bar_shortcode( $atts ) {
        $defaults = array(
            'field' => '',
        );
    
        $atts = shortcode_atts( $defaults, $atts );
    
        if (empty($atts['field'])) {
            return ''; // Field parameter is required
        }
    
        // Check if the field is 'grand_total'
        $is_grand_total = ($atts['field'] === 'grand_total');
    
        // Fields to calculate the average
        $fields_to_average = array('besimi', 'lojrat', 'bonuse', 'sherbimi');
    
        // Get the post ID
        $post_id = get_the_ID();
    
        // If it's 'grand_total', calculate the average of the specified fields
        if ($is_grand_total) {
            $total_ratings = 0;
    
            foreach ($fields_to_average as $field) {
                $rating = get_field($field, $post_id);
    
                if ($rating === false) {
                    return ''; // Field not found or empty
                }
    
                $total_ratings += $rating;
            }
    
            $average_rating = $total_ratings / count($fields_to_average);
    
            // Set the field to empty to avoid displaying any label
            $atts['field'] = '';
        } else {
            // Otherwise, get the rating for the specified field
            $rating_term = get_field($atts['field'], $post_id);
    
            if ($rating_term === false) {
                return ''; // Field not found or empty
            }
    
            $average_rating = $rating_term;
        }
    
        $prefix = 'star-bar-' . sanitize_title($atts['field']) . '-';
        $uniqueClass = uniqid($prefix);
        $percentage = 100 * $average_rating / 5;
    
        $html = '<span class="'.$uniqueClass.'">★★★★★</span>
            <style>
            .'.$uniqueClass.' {
                background: linear-gradient(90deg, #ffd32a ' . $percentage .'%, rgba(0,0,0,1) '. $percentage.'%);
                color: rgba(0,0,0,0);
                background-clip: text;
                -webkit-background-clip: text;
    			font-size: 1.1em;
                line-height: 1em;
                font-weight: 900;
    			letter-spacing: 2.5px;
            }
            </style>
            <script type="application/ld+json">
                {
                  "@context": "https://schema.org",
                  "@type": "Rating",
                  "ratingValue": '.$average_rating.',
                  "bestRating": "5",
                  "worstRating": "1"
                }
            </script>';
    
        return $html;
    }
    
    add_shortcode('star_bar', 'make_star_bar_shortcode');

    Render Block Code:

    add_filter('render_block', function ($block_content, $block) {
        if (!empty($block['attrs']['className']) && 'my-rating' === $block['attrs']['className']) {
            $post_id = get_the_ID();
    
            if (!empty($post_id)) {
                // Get the average rating using the post ID
                $average_rating = get_average_rating($post_id);
    
                // Display the rating value and make it bold
                $block_content = '<strong>' . number_format($average_rating, 1) . '</strong>';
            }
        }
    
        return $block_content;
    }, 10, 2);
    
    function get_average_rating($post_id) {
        $fields_to_average = array('besimi', 'lojrat', 'bonuse', 'sherbimi');
        $total_ratings = 0;
    
        foreach ($fields_to_average as $field) {
            $rating = get_field($field, $post_id);
    
            if ($rating === false) {
                return 0; // Field not found or empty
            }
    
            $total_ratings += $rating;
        }
    
        return $total_ratings / count($fields_to_average);
    }

    Basically, the average rating value is not included in the ACF custom field as it is automatically handled by both codes.

    So what I did was I created a custom field and followed the order query loop by custom field instruction but it’s not working. By the way, the custom field that I’ve created is just manually adding the average rating value but it is not really rendered on the live loop content. Maybe this is the reason?

    Can you please help me make my query loop order by the average star rating?

  • Hi Yeriel,

    To clarify, do you want to order the Query Loop by “get_average_rating”?

    What code do you currently have for the filter? Can you share it as well?

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