Skip to content

Instantly share code, notes, and snippets.

@willybahuaud
Created January 28, 2022 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willybahuaud/fb3daaf63e7f1d0d788b3847bb4bb3fc to your computer and use it in GitHub Desktop.
Save willybahuaud/fb3daaf63e7f1d0d788b3847bb4bb3fc to your computer and use it in GitHub Desktop.
Order post by categories id
<?php
// On tri par par ordre des termes dans la tax_query
add_action( 'pre_get_posts', 'w_filter_query' );
function w_filter_query( $q ) {
if ( ! is_admin() && 'product' == $q->get('post_type') && is_post_type_archive( 'product' ) ) {
$q->set( 'need_special_order', 'tq_order' );
}
}
add_filter('posts_orderby', 'edit_posts_orderby', 100, 2);
function edit_posts_orderby( $orderby_statement, $wp_query ) {
if ( $wp_query->get( 'need_special_order' ) && '' != $wp_query->get( 'need_special_order' ) ) {
$tq = $wp_query->get( 'tax_query' );
if ( ! empty( $tq[ $wp_query->get( 'need_special_order' ) ]['terms'] ) ) {
$order = implode( ', ', $tq[ $wp_query->get( 'need_special_order' ) ]['terms'] );
$orderby_statement = " FIELD( wpsp_term_relationships.term_taxonomy_id, {$order}) ASC, menu_order ASC ";
}
}
return $orderby_statement;
}
<?php
// On filtre les termes à afficher sur la page, via pre_get_posts
add_action( 'pre_get_posts', 'w_woocommerce_posts' );
function w_woocommerce_posts( $q ) {
if ( is_admin() ) {
return false;
}
if ( ! $q->is_main_query() || ! $q->is_post_type_archive( 'product' ) || 'product' != $q->get( 'post_type' ) ) {
return false;
}
// ici une option avec un tableau des ID de termes à afficher sur cette page
$requiered_terms = get_option( 'options_cat_a_afficher', array() );
$tq = $q->get( 'tax_query', array() );
$tq['tq_order'] = array(
'taxonomy' => 'product_cat',
'terms' => $requiered_terms,
);
$q->set( 'tax_query', $tq );
$q->set( 'posts_per_page', -1 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment