当WooCommerce产品搜索返回 "未找到产品 "时,重定向到特定页面。

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

在Woocommerce中,我试图使用下面的代码片段来重定向到我的网站的一个特定页面,而不是在一个空的产品搜索中显示 "没有找到结果"。

现在的短码是 [insert page id="99"] 不工作,并显示 [insert page id="99"] 作为纯文本。如果我使用短码,任何短码如 '[recent_products per_page="4"]' 它显示的是产品,但我想重定向到一个特定的WordPress页面,该页面的帖子ID是99。

remove_action( 'woocommerce_no_products_found', 'wc_no_products_found' );
add_action( 'woocommerce_no_products_found', 'show_products_on_no_products_found', 20 );
function show_products_on_no_products_found() {
    echo '<h4>' . __( 'Are u looking for this?', 'domain' ) . '</h4>';
    echo do_shortcode( '[insert page id="99"]' );
}

但我想重定向到一个特定的WordPress页面,这个页面的ID是99。

当产品搜索返回 "没有找到产品 "时,如何将用户重定向到一个特定的页面?

wordpress woocommerce code-snippets wordpress-shortcode
1个回答
1
投票

使用 template_redirect 钩子,你可以将用户重定向到一个特定的页面,当有 "没有找到结果 "的产品查询搜索,如。

add_action( 'template_redirect', 'no_products_found_redirect' );
function no_products_found_redirect() {
    global $wp_query; 
    if( isset($_GET['s']) && isset($_GET['post_type']) && 'product' === $_GET['post_type'] 
    && ! empty($wp_query) && $wp_query->post_count == 0 ) {
        wp_redirect( get_permalink( 99 ) );
        exit();
    }
}

代码在你的活动子主题(或活动主题)的function.php文件中。经过测试,可以使用。

© www.soinside.com 2019 - 2024. All rights reserved.