//Save product attributes to post metadata when a product is saved.
add_action('save_post', 'wh_save_product_custom_meta', 10, 3);
function wh_save_product_custom_meta($post_id, $post, $update)
{
$post_type = get_post_type($post_id);
// If this isn't a 'product' post, don't update it.
if ($post_type != 'product')
return;
if (!empty($_POST['attribute_names']) && !empty($_POST['attribute_values']))
{
$attribute_names = $_POST['attribute_names'];
$attribute_values = $_POST['attribute_values'];
foreach ($attribute_names as $key => $attribute_name)
{
switch ($attribute_name)
{
//for length (int)
case 'pa_length':
if (!empty($attribute_values[$key][0]))
{
update_post_meta($post_id, 'pa_length', $attribute_values[$key][0]);
}
break;
}
}
}
}
//Main ordering logic for orderby attribute
add_filter('woocommerce_get_catalog_ordering_args', 'wh_catalog_ordering_args');
function wh_catalog_ordering_args($args)
{
global $wp_query;
if (isset($_GET['orderby']))
{
switch ($_GET['orderby'])
{
//for attribute/taxonomy=pa_length
case 'pa-length-asc' :
$args['order'] = 'ASC';
$args['meta_key'] = 'pa_length';
$args['orderby'] = 'meta_value_num'; //because length is an int
break;
case 'pa-length-desc' :
$args['order'] = 'DESC';
$args['meta_key'] = 'pa_length';
$args['orderby'] = 'meta_value_num'; //because length is an int
break;
}
}
return $args;
}
//Lets add the created sorting order to the dropdown list.
add_filter('woocommerce_default_catalog_orderby_options', 'wh_catalog_orderby');
add_filter('woocommerce_catalog_orderby', 'wh_catalog_orderby');
function wh_catalog_orderby($sortby)
{
$sortby['pa-length-asc'] = 'Sort by Length: Small - Large';
$sortby['pa-length-desc'] = 'Sort by Length: Large - Small';
return $sortby;
}
Code va dans le fichier function.php de votre thème enfant actif (ou le thème). Ou encore dans tous les fichiers php plugin.
Le code a été testé et fonctionne.
Veuillez noter: Comme vous n'avez mentionné aucun nom de champ, j'ai donc écrit une réponse plus générale, si vous voulez une réponse spécifique, veuillez mettre à jour votre question avec votre nom d'attribut/slug. .
Référence: Custom Order By Attributes
Je suis en train de tester cela avec une petite gamme de produits en ajoutant maintenant et en vérifiant si cela fonctionne vous reviendra bientôt. Merci d'avoir pris le temps en premier lieu! – Sjoerd89
Comme posté pas sûr pourquoi cela ne fonctionne pas pour moi, j'ai re - ajouté des produits et la commande par est là. Mais quand je le commande, il change les produits mais pas par cet attribut. – Sjoerd89
Avez-vous vérifié dans db ce qui est inséré dans la table 'wp_postmeta'? et pouvez-vous me donner une valeur d'attribut d'échantillon. –