Support

Account

Forum Replies Created

  • There was an error sorry :

    function custom_order_by_acf_field_query($query) {
        if (!is_admin() && isset($query->query_vars['orderby'])) {
    		// Récupérer le champ ACF entre {{}}
    		$orderby_field = str_replace(array('{{', '}}'), '', $query->query_vars['orderby']);
    		 if ( $orderby_field != $query->query_vars['orderby']) {
    			$query->set('meta_key', $orderby_field);
    			$query->set('orderby', 'meta_value_num');
    		 }
        }
    }
  • Here is a code that I improved, perfectly generic that everyone can use.
    Just put in the order field of your component, the acf field enters {{}} and it will sort in the correct order.

    function custom_order_by_acf_field_query($query) {
        if (!is_admin()) {
            if (isset($query->query_vars['orderby'])) {
                // Récupérer le champ ACF entre {{}}
                $orderby_field = str_replace(array('{{', '}}'), '', $query->query_vars['orderby']);
    
    			 if (is_string($orderby_field)) {
                // Concaténer avec le préfixe "_" pour former la clé de méta ACF
                $meta_key = '_'.$orderby_field;
    
                // Vérifier si le champ ACF est spécifié dans la requête
                if (metadata_exists('post', $query->get('post_type'), $meta_key)) {
                    $query->set('meta_key', $meta_key);
                    $query->set('orderby', 'meta_value_num');
                    // $query->set('order', 'DESC'); // Vous pouvez définir l'ordre ici si nécessaire
                }
    			 }
            }
        }
    }
    
    add_action('pre_get_posts', 'custom_order_by_acf_field_query');
  • With a lot of research and testing, I believe that it is indeed impossible to do so with an ACF field. you must therefore modify it via a function in functions.php that I wrote and that I share with you

    function custom_order_by_acf_field_query($query) {
    
        if ( !is_admin()) { 
    		if(isset($query->query_vars['orderby']) && $query->query_vars['orderby'] == '{{coefficient}}') {
                $query->set('meta_key', 'coefficient');
                $query->set('orderby', 'meta_value_num');
                $query->set('order', 'DESC');
    		}
    
        }
    }
    
    add_action('pre_get_posts', 'custom_order_by_acf_field_query');
Viewing 3 posts - 1 through 3 (of 3 total)