Woocommerce:当类别只包含一个项目时如何直接跳转到产品页面

Sim*_*mon 2 wordpress woocommerce

我有一个顶部菜单,允许显示产品类别。在这种情况下,我销售的应用程序的名称。

单击此菜单项时,它会显示类别的内容 - 正如它应该做的那样。

但是,由于这个类别只包含一个项目,我想直接跳转到产品页面,而不是显示一个包含一个项目的类别页面。

这是相关页面的链接:Boutique.zimrahapp.com/categorie-produit/app/

我找不到可以调整输出或进行重定向的挂钩或模板。

这种事情已经做过了吗?

hel*_*ing 7

WooCommerce 将只有一个结果的搜索查询重定向到该结果。您可以在这里看到他们是如何做的。

修改他们的代码你会得到这样的结果:

function so_35012094_template_redirect() {
    global $wp_query;

    // Redirect to the product page if we have a single product
    if ( is_product_category() && 1 === $wp_query->found_posts ) {
        $product = wc_get_product( $wp_query->post );
        if ( $product && $product->is_visible() ) {
            wp_safe_redirect( get_permalink( $product->id ), 302 );
            exit;
        }
    }

}
add_action( 'template_redirect', 'so_35012094_template_redirect' );
Run Code Online (Sandbox Code Playgroud)

未经测试,因此请注意复制/粘贴失败。经常使用WP_DEBUG这样你就能找出问题所在。


AJD*_*AJD 5

上面的代码对我不起作用。我有一个有效的解决方案,但它重定向了所有单个存档结果。就我而言,我还想重定向单个标签。

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

function redirect_to_single_post(){
global $wp_query;
if( is_archive() && $wp_query->post_count == 1 ){
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)

我在这里问过同样的问题:Woocommerce:如果类别页面上只有一个产品,如何自动重定向到单个产品?