本文介绍了Woocommerce:如果类别页面上只有一个产品,如何自动重定向到单个产品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当类别中只有一个产品时,我试图跳过类别存档页面并直接转到单个产品页面.

I'm trying to skip the category archive page and go straight to the single product page when there is only one product in the category.

这是我到目前为止的代码,(不工作):

Here is the code I have so far, (not working):

add_action( 'template_redirect', 'woo_redirect_single_product_cat', 10 );

function woo_redirect_single_product_cat() {

global $wp_query, $wp;;

if  ( is_post_type_archive( 'product' ) && 1 === $wp_query->found_posts  ) {

    $product = wc_get_product($wp_query->post->ID);

       if ( $product && $product->is_visible() ) {
            wp_safe_redirect( get_permalink( $product->id ), 302 );
            exit;

       }
}
}

此代码仿照 Woocommerce 中的单一搜索重定向:

This code is modeled after the single search redirect in Woocommerce:

https://github.com/woothemes/woocommerce/blob/fce8dc0868439474c24f7317af50ce7627f0d1c1/includes/wc-template-functions.php#L43

谢谢!

推荐答案

我想通了,但不是专门针对 Woocommerce 的:(现在是.)

I figured it out, but not specifically for Woocommerce: (edit: now it is.)

/* Redirect if there is only one product in the category or tag, or anywhere... */

function redirect_to_single_post(){
global $wp_query;
if( (is_product_category() || is_product_tag()) && $wp_query->post_count == 1 )//Woo single only
//if( is_archive() && $wp_query->post_count == 1 )//redirect all single posts 
{
    the_post();
    $post_url = get_permalink();
    wp_safe_redirect($post_url , 302 );
exit;
}
} 
add_action('template_redirect', 'redirect_to_single_post');

在某种程度上,这更好,因为它也可以重定向单个标签.

In a way this is even better because it redirects for single tags as well.

这篇关于Woocommerce:如果类别页面上只有一个产品,如何自动重定向到单个产品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 03:41