Woocommerce:如果类别页面上只有一个产品,如何自动重定向到单个产品?

AJD*_*AJD 1 redirect woocommerce

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

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

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;

       }
}
}
Run Code Online (Sandbox Code Playgroud)

此代码以 Woocommerce 中的单个搜索重定向为模型:

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

谢谢!

AJD*_*AJD 6

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

/* 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');
Run Code Online (Sandbox Code Playgroud)

在某种程度上,这甚至更好,因为它也为单个标签重定向。