Skip to content

Instantly share code, notes, and snippets.

@willybahuaud
Created January 28, 2022 23:38
Show Gist options
  • Select an option

  • Save willybahuaud/fb3daaf63e7f1d0d788b3847bb4bb3fc to your computer and use it in GitHub Desktop.

Select an option

Save willybahuaud/fb3daaf63e7f1d0d788b3847bb4bb3fc to your computer and use it in GitHub Desktop.

Revisions

  1. Willy Bahuaud created this gist Jan 28, 2022.
    20 changes: 20 additions & 0 deletions filtre-order.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    <?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;
    }
    23 changes: 23 additions & 0 deletions ma-requete.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    <?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 );
    }