如何按ID排序不随机化Woocommerce的相关产品

时间:2018-06-02 12:13:57

标签: php wordpress woocommerce

Woocommerce默认显示在单个产品页面中的相关产品部分,它以随机模式检索4个具有相同类别或标签的产品。

所以每次你重新加载页面或第二天访问页面时它都会显示每次不同的相关产品,这对SEO来说不是一个好选择,因为这样就不会在页面之间传递链接汁。

所以我想尝试按顺序ID顺序显示相关产品。

据我所知,woocommerce通过使用orderby =' rand'随机推断相关产品。查询中的函数

然后尝试使用主题的function.php中的此片段找到可以在orderby = 'ID'orderby = 'post__in'中更改此值的过滤器:

add_filter('woocommerce_output_related_products_args', 'wh_related_products_args');

    function wh_related_products_args($args)
    { 
            $args['orderby'] = 'ID'; // or  $args['orderby'] = 'post__in';

        return $args;
    }

但不起作用

related.php中的代码是

<?php
/**
 * Related Products
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/single-product/related.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     3.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( $related_products ) : ?>

    <section class="related products">

        <h2><?php esc_html_e( 'Related products', 'woocommerce' ); ?></h2>

        <?php woocommerce_product_loop_start(); ?>

            <?php foreach ( $related_products as $related_product ) : ?>

                <?php
                    $post_object = get_post( $related_product->get_id() );

                    setup_postdata( $GLOBALS['post'] =& $post_object );

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

            <?php endforeach; ?>

        <?php woocommerce_product_loop_end(); ?>

    </section>

<?php endif;

wp_reset_postdata();

我做错了什么?

1 个答案:

答案 0 :(得分:0)

在活动主题的functions.php中添加以下代码。

add_filter( 'woocommerce_product_related_posts','wpse_123436_change_wc_related_products_relation_to_and' );
function wpse_123436_change_wc_related_products_relation_to_and() {
   $get_related_products_args = array(
              'orderby' => 'id', // you can place id,title over here. 
              'order'     => 'ASC',
            );
   return $get_related_products_args;
}