【问题标题】:How to limit query in price filter如何在价格过滤器中限制查询
【发布时间】:2016-02-09 11:12:01
【问题描述】:

如何在 woocommerce 产品价格过滤器短代码 [products_by_price min="100" max="300"] 中将查询限制为 6?以下代码基于 woocommerce 产品短代码,遗憾的是不支持 per_page。在这种情况下,我需要将查询限制为 6 以避免显示所有产品。

add_shortcode( 'wc_products_price_range', 'wc_products_price_range' );
function wc_products_price_range( $atts, $content, $shortcode ) {
    if ( class_exists( 'WooCommerce' ) ) {
        $shortcodes = new WC_Shortcodes();
        if ( is_array( $atts ) ) {
            $min = (int) $atts['min'];
            $max = (int) $atts['max'];
            if ( $min && $max ) {
                $and = "meta_value BETWEEN $min AND $max";
            } else {
                if ( $min ) {
                    $and = "meta_value >= $min";
                } elseif ( $max ) {
                    $and = "meta_value <= $max";
                }
            }
            if ( $and ) {
                global $wpdb;
                $query = "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_price' AND $and";
                $ids = $wpdb->get_col( $query );
                if ( ! empty( $ids ) ) {
                    $atts['ids'] = implode( ",", $ids );
                }
            }
        }
        return $shortcodes->products( $atts );
    }
}

【问题讨论】:

    标签: wordpress woocommerce limit


    【解决方案1】:

    在快速浏览 WC 短代码类后,我发现了这个:

    public static function products( $atts ) {
        $atts = shortcode_atts( array(
            'columns' => '4',
            'orderby' => 'title',
            'order'   => 'asc',
            'ids'     => '',
            'skus'    => ''
        ), $atts );
    

    这意味着您可以将“column”属性与 id 一起传递,您可以在其中限制每页的帖子。

    在这个查询中:

       $query = "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_price' AND $and";
    

    您可以将限制 0,6 与 order by 子句一起使用。 希望这可以帮助。 或者

    随机行:

    SELECT * FROM `table` WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` ) ORDER BY id LIMIT 1;
    

    或者您可以将“rand”传递给短代码中的属性。

    【讨论】:

    • 适用于限制 '$query = "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_price' AND $and limit 0,6";'但它只显示数据库的前 6 个结果。有没有办法可以显示任何 6 个结果?干杯!
    • 尝试从 wp_postmeta 限制 6 中选择 floor(RAND() * (SELECT MAX(post_id) FROM wp_postmeta))
    猜你喜欢
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多