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

问题描述 投票:0回答:1

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();

我究竟做错了什么 ?

php wordpress woocommerce
1个回答
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.