Home › Forums › General Issues › Can’t sort with an ACF field? › Reply To: Can’t sort with an ACF field?
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');
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.