为WP站点创建一些过滤器

时间:2016-11-24 08:25:59

标签: php wordpress plugins filter

我为WP网站创建了一些产品过滤器。我找到了这个PHP脚本:

$GLOBALS['my_query_filters'] = array( 
    'field_1'   => 'forma', 
    'field_2'   => 'posa',
    'field_3'   => 'conduttore',
    'field_4'   => 'isolante',
    'field_5'   => 'raggio_minimo_di_curvatura',
    'field_6'   => 'guaina',
    'field_7'   => 'marchiatura',
    'field_8'   => 'tensione_di_esercizio',
    'field_9'   => 'temp_max_esercizio',
    'field_10'  => 'temp_min_di_inst',
    'field_11'  => 'temp_max_corto'
);


// action
add_action('pre_get_posts', 'my_pre_get_posts', 10, 1);

function my_pre_get_posts( $query ) {

    // bail early if is in admin
    if( is_admin() ) {

        return;

    }


    // get meta query
    $meta_query = $query->get('meta_query');


    // loop over filters
    foreach( $GLOBALS['my_query_filters'] as $key => $name ) {

        // continue if not found in url
        if( empty($_GET[ $name ]) ) {

            continue;

        }


        // get the value for this filter
        // eg: http://www.website.com/events?city=melbourne,sydney
        $value = explode(',', $_GET[ $name ]);


        // append meta query
        $meta_query[] = array(
            'key'       => $name,
            'value'     => $value,
            'compare'   => 'IN',
        );

    } 


    // update meta query
    $query->set('meta_query', $meta_query);

}

其中$ GLOBALS [' my_query_filters']由我根据找到的路线创建。我将此代码插入到function.php文件中。

这是商店页面代码:

<?php
/**
 * The Template for displaying product archives, including the main shop page which is a post type archive
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/archive-product.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see         https://docs.woocommerce.com/document/template-structure/
 * @author      WooThemes
 * @package     WooCommerce/Templates
 * @version     2.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

get_header( 'shop' ); ?>





    <?php
        /**
         * woocommerce_before_main_content hook.
         *
         * @hooked woocommerce_output_content_wrapper - 10 (outputs opening divs for the content)
         * @hooked woocommerce_breadcrumb - 20
         */
        do_action( 'woocommerce_before_main_content' );
    ?>

        <?php if ( apply_filters( 'woocommerce_show_page_title', true ) ) : ?>

            <h1 class="page-title"><?php woocommerce_page_title(); ?></h1>

        <?php endif; ?>
        <div id="archive-filters">
            <?php foreach( $GLOBALS['my_query_filters'] as $key => $name ): 

                // get the field's settings without attempting to load a value
                $field = get_field_object($key, false, false);


                // set value if available
                if( isset($_GET[ $name ]) ) {

                    $field['value'] = explode(',', $_GET[ $name ]);

                }


                // create filter
                ?>
                <div class="filter" data-filter="<?php echo $name; ?>">
                    <?php create_field( $field ); ?>
                </div>

            <?php endforeach; ?>
            </div>

            <script type="text/javascript">
            (function($) {

                // change
                $('#archive-filters').on('change', 'input[type="checkbox"]', function(){

                    // vars
                    var url = '<?php echo home_url('property'); ?>';
                        args = {};


                    // loop over filters
                    $('#archive-filters .filter').each(function(){

                        // vars
                        var filter = $(this).data('filter'),
                            vals = [];


                        // find checked inputs
                        $(this).find('input:checked').each(function(){

                            vals.push( $(this).val() );

                        });


                        // append to args
                        args[ filter ] = vals.join(',');

                    });


                    // update url
                    url += '?';


                    // loop over args
                    $.each(args, function( name, value ){

                        url += name + '=' + value + '&';

                    });


                    // remove last &
                    url = url.slice(0, -1);


                    // reload page
                    window.location.replace( url );


                });

            })(jQuery);
            </script>



        <?php
            /**
             * woocommerce_archive_description hook.
             *
             * @hooked woocommerce_taxonomy_archive_description - 10
             * @hooked woocommerce_product_archive_description - 10
             */
            do_action( 'woocommerce_archive_description' );
        ?>

        <?php if ( have_posts() ) : ?>

            <?php
                /**
                 * woocommerce_before_shop_loop hook.
                 *
                 * @hooked woocommerce_result_count - 20
                 * @hooked woocommerce_catalog_ordering - 30
                 */
                do_action( 'woocommerce_before_shop_loop' );
            ?>

            <?php woocommerce_product_loop_start(); ?>

                <?php woocommerce_product_subcategories(); ?>

                <?php while ( have_posts() ) : the_post(); ?>

                    <?php wc_get_template_part( 'content', 'product' ); ?>

                <?php endwhile; // end of the loop. ?>

            <?php woocommerce_product_loop_end(); ?>

            <?php
                /**
                 * woocommerce_after_shop_loop hook.
                 *
                 * @hooked woocommerce_pagination - 10
                 */
                do_action( 'woocommerce_after_shop_loop' );
            ?>

        <?php elseif ( ! woocommerce_product_subcategories( array( 'before' => woocommerce_product_loop_start( false ), 'after' => woocommerce_product_loop_end( false ) ) ) ) : ?>

            <?php wc_get_template( 'loop/no-products-found.php' ); ?>

        <?php endif; ?>

    <?php
        /**
         * woocommerce_after_main_content hook.
         *
         * @hooked woocommerce_output_content_wrapper_end - 10 (outputs closing divs for the content)
         */
        do_action( 'woocommerce_after_main_content' );
    ?>

    <?php
        /**
         * woocommerce_sidebar hook.
         *
         * @hooked woocommerce_get_sidebar - 10
         */
        do_action( 'woocommerce_sidebar' );
    ?>

<?php get_footer( 'shop' ); ?>

结果仅在商店页面中有十个空行(插入到数组中的相同过滤器编号)但其他没有任何反应。 如何完成过滤器创建? 我可以在meta_query期望嵌套数组之间添加关系吗? 你能帮我吗? 谢谢!

2 个答案:

答案 0 :(得分:0)

也许你可以用foreach循环和var名称改变一些东西。

我重写了my_pre_get_posts()

function my_pre_get_posts( $query ) {

    // bail early if is in admin
    if( is_admin() || !is_main_query() ) {
        return;
    }

    // get meta query
    $meta_query = $query->get('meta_query');
    $meta_queries = array();

    foreach( $GLOBALS['my_query_filters'] as $key => $name ) {

        // continue if not found in url
        if( empty($_GET[ $name ]) ) {
            continue;
        }

        $value = explode(',', $_GET[ $name ]);

        $meta_queries[] = array(
            'key'       => $name,
            'value'     => $value,
            'compare'   => 'IN',
        );
    }

    $meta_query = array(
        'relation' => 'AND',          
            $meta_queries       
    );
    // update meta query
    $query->set('meta_query', $meta_query);

}

此处$meta_queries附加到$meta_query期望的嵌套数组。

在我不关心$meta_query = $query->get('meta_query');的函数中。

希望它有所帮助。

答案 1 :(得分:0)

试试这个:

function my_pre_get_posts($ query){

// bail early if is in admin
if( is_admin() || !is_main_query() ) {
    return;
}

// get meta query
$meta_queries = $query->get('meta_query');

foreach( $GLOBALS['my_query_filters'] as $key => $name ) {

    // continue if not found in url
    if( empty($_GET[ $name ]) ) {
        continue;
    }

    $value = explode(',', $_GET[ $name ]);

    $meta_queries[] = array(
        'key'       => $name,
        'value'     => $value,
        'compare'   => 'IN',
    );
}

$meta_query = array(
    'relation' => 'AND',          
        $meta_queries       
);
// update meta query
$query->set('meta_query', $meta_query);

}