admin管理员组

文章数量:1122832

function display_hi_vis_products_with_orange_hi_vis( $query ) {
    // Ensure this only runs on the front end, and only on the main query
    if ( ! is_admin() && $query->is_main_query() ) {

        // Check if we're on the 'hi-vis' custom taxonomy with the term ID '64264'
        if ( is_tax( 'hi-vis', 64264 ) ) {
            
            // If no products are directly associated with this taxonomy term, display products from the entire shop filtered by 'Orange Hi Vis'
            
            // Remove any taxonomy restrictions so we can fetch products from the whole shop
            $query->set( 'tax_query', array() ); 

            // Filter products by the custom meta key 'iconic_cffv_37_colour' with the value 'Orange Hi Vis'
            $meta_query = array(
                array(
                    'key'     => 'iconic_cffv_37_colour',
                    'value'   => 'Orange Hi Vis',
                    'compare' => '='
                ),
            );

            // Apply the meta query to the main query
            $query->set( 'meta_query', $meta_query );

            // Display 10 products per page
            $query->set( 'posts_per_page', 10 );

            // Handle pagination
            $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
            $query->set( 'paged', $paged );
        }
    }
}
add_action( 'pre_get_posts', 'display_hi_vis_products_with_orange_hi_vis' );

I'm trying to display products from a custom field on a taxonomy archive page (that has 0 products assigned to it in Wordpress).

I'm trying to override the main shop loop, and instead use a custom query.

The problem is I can't seem to override the default loop, and the tax archive always shows '0 products'.

I tested the query loop in a custom template theme taxonomy-hi-vis.php and the products displayed perfectly - only issue was the output was limited to XX products and I couldn't get the default WooCommerce pagination to display.

Any help would be greatly appreciated!

本文标签: customizationQuerying a meta field on a custom taxonomy archive