advanced-custom-fieldscustom-fieldsdivi-theme

Sort divi blog module elements by custom field?


I am using Theme: Divi and Plugin: ACF - Advanced Custom Fields for custom field. I read How to show custom fields in divi blog module? and the @msmarymak solution helped me a lot ! But now I woudl like to be able to sort post showed in the custom blog module by the custom field I created in ACF (dates or location). Any idea is welcome!


Solution

  • If you have, for example, an ACF Date Picker field called "event_date", then you can do it using code such as this:

    add_filter('init', 'db_acf_sort_initialize_blog_module_sorting');
    
    function db_acf_sort_initialize_blog_module_sorting() {
        add_filter('et_pb_module_shortcode_attributes', 'db_acf_sort_add_sorting_filter', 10, 3);
        add_filter('et_pb_blog_shortcode_output', 'db_acf_sort_remove_sorting_filter', 10, 2);
    }
    
    function db_acf_sort_add_sorting_filter($attrs, $content, $module_slug) {
        if ($module_slug !== 'et_pb_blog') {
            return $attrs;
        }
        add_filter('pre_get_posts', 'db_acf_sort_sort_blog_module_posts_by_acf', 10, 1);
        return $attrs;
    }
    
    function db_acf_sort_remove_sorting_filter($output, $attrs) {
        remove_filter('pre_get_posts', 'db_acf_sort_sort_blog_module_posts_by_acf', 10);
        return $output;
    }
    
    function db_acf_sort_sort_blog_module_posts_by_acf($query) {
        
        $acf_field_name = 'event_date'; // Change this to your ACF field's name
    
        $query->set('meta_key', $acf_field_name);
        $query->set('orderby', 'meta_value');
        $query->set('order', 'ASC');  // ASC for earliest events first, use DESC for reverse
        
        return $query;
    }
    

    When processing of the blog module begins, it registers a pre_get_posts filter which changes the blog module query to sort by the meta key containing the ACF date. Once processing of the blog module is complete, it removes it again to avoid affecting anything.

    Change the 'event_date' to the name of your ACF field, and if necessary change the sort order from 'ASC' to 'DESC' to reverse the results.

    Some additional details / screenshots here:

    Divi Booster: How to Sort Divi Blog Module Posts by an ACF Field