Senior PHP Engineer | Former E-commerce Website Manager | Full Stack Web Developer

Redirect draft WooCommerce products

I received a feature request for an ecommerce website that required redirection of customers from product pages to a different page if the product (or post as referred to by WordPress) is in draft status.

The company needed to reduce the size of its inventory, and was concerned about the increase of 404 errors on the website having a negative impact. Instead, they wanted to redirect the customer to a page that provides more context.

You can use the WordPress template_redirect hook to detect 404 errors and check if the requested page is a single product page, and then use get_post_status() to detect if the product is draft. Here’s an example code snippet:

add_action( 'template_redirect', 'redirect_draft_products' );

function redirect_draft_products() {
	// check if error 404, and that the visitor is trying to view a product
    if ( is_404() && strpos( $_SERVER['REQUEST_URI'], '/product/' ) !== false ) {
        // Get the product slug
        $parts = explode( '/', $_SERVER['REQUEST_URI'] );
        $product_slug = end( $parts );

        // Check if a product with this slug exists
        $product = get_page_by_path( $product_slug, OBJECT, 'product' );
        if ( $product ) {

				// Get the product status
				$product_status = get_post_status( $product->ID );
	
	            // Redirect to the product page
				if ( $product_status === 'draft' ) {
					wp_redirect(  get_permalink( '90329' ) ); // ID of the page to redirect to
					exit;
				}
            exit;
        }
    }
}

The benefit of the above snippet over other snippets I have seen is by checking for 404 errors, you’ll be able to make sure that draft product aren’t redirected if an admin is logged in.

This code adds an action to the template_redirect hook, which is fired when a page is loaded. It checks if the current page is a 404 error using the is_404() function. If so, it checks if the URL contains the string ‘/product/’ using the strpos() function.

If the URL contains ‘/product/’, the code extracts the product slug from the URL and checks if a product with this slug exists using the get_page_by_path() function. If a product exists, the code redirects the user to the product page using the wp_redirect() function and exits the script using exit. This ensures that the user is redirected immediately and prevents any further code from executing.

Why you want to prevent 404 errors

404 errors are bad because they indicate that a requested page could not be found on the server. This can negatively impact user experience because it can lead to frustration and confusion. Additionally, search engines may interpret 404 errors as a sign that a website is poorly maintained, which can result in lower search engine rankings.

Facebook
Twitter
LinkedIn
Pinterest
Email