最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

woocommerce offtopic - Redirect no product url's to static url

programmeradmin2浏览0评论

I am trying to redirect non-existing woocommerce product's url's to worpdress page.

Example:

to

here there is no product published as abc.

also i have few working products at .

i tried with .htaccess but looks like it's not possible to use .htaccess in this case.

Thanks in advance.

I am trying to redirect non-existing woocommerce product's url's to worpdress page.

Example:

https://testname/product/abc to https://testname/sample-page

here there is no product published as abc.

also i have few working products at https://testname/product/def.

i tried with .htaccess but looks like it's not possible to use .htaccess in this case.

Thanks in advance.

Share Improve this question asked May 6, 2020 at 16:49 Ramkumar MRamkumar M 8741 gold badge13 silver badges33 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

If you prefer more control in coding, you may use

  • request hook - test the WordPress query after it is being setup
  • preg_match() - match /product/ keyword
  • url_to_postid() - test if product url exists

to build a checking when WordPress query is being setup. The advantage of code against .htaccess is that it is relatively server independent such as server migration, site migration and so on.

The following code is placed in theme functions.php and proved to work in a testing site.

add_filter( 'request', 'ws365986_check_request' );
function ws365986_check_request( $query ) {
    // var_dump($_SERVER['REQUEST_URI']); // for debug

    // only check for product url if /product/ is found in URL
    if( isset( $_SERVER['REQUEST_URI'] ) && preg_match( '/\/product\//', $_SERVER['REQUEST_URI'], $matches ) ) {
        // check if url product exist
        if( empty( url_to_postid( $_SERVER['REQUEST_URI'] ) ) ) {
            // redirect if return is 0 (empty)

            $url = home_url( '/sample-page' );
            // wp_redirect( $url ); // because $url is prepared by internally, wp_redirect should be enough
            wp_safe_redirect( $url );
            exit(); // exit script after redirect
        }
    }

    // default
    return $query;
}

It is possible with the .htaccess file, add the below rule in the .htaccess:

Redirect 301 https://testname/product/abc https://testname/sample-page

or

Redirect 301 /product/abc /sample-page

发布评论

评论列表(0)

  1. 暂无评论