0

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

Example:

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

here there is no product published as abc.

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

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

Thanks in advance.

2 Answers 2

1

If you prefer more control in coding, you may use

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;
}
3
  • Thanks. It really works but it display in header string(12) "/sample-page"
    – Ramkumar M
    May 8, 2020 at 16:38
  • 1
    Hi sorry that forgotten to add notes ane comment out the var_dump function which is for debug. May 8, 2020 at 20:24
  • 1
    I have updated the answer. Thanks for the feedback! May 8, 2020 at 20:47
0

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

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

or

Redirect 301 /product/abc /sample-page

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.