Skip to content

Instantly share code, notes, and snippets.

@yanknudtskov
Created March 12, 2020 12:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yanknudtskov/18666c64def6cf693130750b241fcd8d to your computer and use it in GitHub Desktop.
Save yanknudtskov/18666c64def6cf693130750b241fcd8d to your computer and use it in GitHub Desktop.
WooCommerce Products per page dropdown
<?php
add_action( 'woocommerce_before_shop_loop', 'yanco_products_per_page_selectbox', 25 );
function yanco_products_per_page_selectbox() {
$html = '';
$style = 'font-size: 16px;
font-weight: 300;
font-family: inherit;
letter-spacing: 1px;
text-transform: uppercase;
width: 289px;
text-align: right;
background-color: #355477;
color: white;';
$per_page = filter_input( INPUT_GET, 'perpage', FILTER_SANITIZE_NUMBER_INT );
$orderby_options = array(
'12' => '12 produkter per side',
'20' => '20 produkter per side',
'40' => '40 produkter per side',
'64' => '64 produkter per side',
);
$html .= '<div class="woocommerce-perpage" style="text-align: right;">';
$html .= '<select style="' . $style . '" onchange="if (this.value) window.location.href=this.value">';
foreach( $orderby_options as $value => $label ) {
$per_page_value = '';
if ( isset( $_GET['orderby'] ) ) {
$per_page_value = $value . '&orderby=' . $_GET['orderby'];
} else {
$per_page_value = $value;
}
$html .= '<option ' . selected( $per_page, $value ) . ' value="?perpage=' . $per_page_value . '#main-archive-products">' . $label. '</option>';
}
$html .= '</select>';
$html .= '</div>';
echo $html;
}
add_action( 'pre_get_posts', 'yanco_products_per_page_pre_get_posts', 200 );
function yanco_products_per_page_pre_get_posts( $query ) {
$per_page = filter_input( INPUT_GET, 'perpage', FILTER_SANITIZE_NUMBER_INT );
if( $query->is_main_query() && !is_admin() && is_product_category() ) {
$query->set( 'posts_per_page', $per_page );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment