【问题标题】:Create some filters for a WP site为 WP 网站创建一些过滤器
【发布时间】:2017-04-08 10:52:48
【问题描述】:

我必须为我的 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 需要嵌套数组之间添加一个关系吗? 你能帮我吗? 谢谢!

【问题讨论】:

    标签: php wordpress plugins filter


    【解决方案1】:

    也许您可以使用 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-&gt;get('meta_query');

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      试试这个:

      函数 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);
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-15
        • 1970-01-01
        • 1970-01-01
        • 2013-07-12
        • 1970-01-01
        • 1970-01-01
        • 2010-12-15
        • 1970-01-01
        相关资源
        最近更新 更多