在所需页面的WordPress上添加功能下拉菜单

时间:2019-02-26 08:40:50

标签: php wordpress woocommerce

我已经做了一个功能,理论上应该在Woocommerce下拉菜单中更改产品的显示数量。该函数来自另一个线程。

我的问题是如何在要显示的页面上显示下拉菜单?

这是功能

add_action( 'woocommerce_before_shop_loop', 'ps_selectbox', 25 );
function ps_selectbox() {
    $per_page = filter_input(INPUT_GET, 'perpage', FILTER_SANITIZE_NUMBER_INT);     
    echo '<div class="dropdown2">';
    echo '<button onclick="myPage()" class="dropbtn">Per page </button>';
    echo '<div id="myPage" class="dropdown-content">';
    $orderby_options = array(
        '15' => '15',
        '20' => '20',
        '50' => '50',
        '75' => '75',
        '150' => '150',
        '200' => '200'
    );
    foreach( $orderby_options as $value => $label ) {
        echo "<a ".selected( $per_page, $value )." onchange="if (this.value) window.location.href=this.value" value='?perpage=$value'>$label</a>";
    }
    echo '</div>';
    echo '</div>';
}

add_action( 'pre_get_posts', 'ps_pre_get_products_query' );
function ps_pre_get_products_query( $query ) {
    $per_page = filter_input(INPUT_GET, 'perpage', FILTER_SANITIZE_NUMBER_INT);
    if( $query->is_main_query() && !is_admin() && is_post_type_archive( 'product' ) ) {
        $query->set( 'posts_per_page', $per_page );
    }
}

1 个答案:

答案 0 :(得分:1)

if(!function_exists('ps_selectbox')){
    function ps_selectbox() {
        $per_page = filter_input(INPUT_GET, 'perpage', FILTER_SANITIZE_NUMBER_INT);     
        echo '<div class="dropdown2">';
        echo '<button onclick="myPage()" class="dropbtn">Per page </button>';
        echo '<div id="myPage" class="dropdown-content">';
        $orderby_options = array(
            '15' => '15',
            '20' => '20',
            '50' => '50',
            '75' => '75',
            '150' => '150',
            '200' => '200'
        );
        foreach( $orderby_options as $value => $label ) {
            echo "<a ".selected( $per_page, $value )." onchange='if (this.value) window.location.href=this.value' value='?perpage=$value'>$label</a>";
        }
        echo '</div>';
        echo '</div>';
    }
}

将其添加到functions.php中,并调用函数ps_selectbox()

function render_ps_selectbox() {
    return ps_selectbox();
}
add_shortcode( 'ps_selectbox', 'render_ps_selectbox' );

在页面构建器中使用[ps_selectbox]