如何修改WooCommerce代码实现指定产品页定向到对应镜像页?
Got it, let's adjust your existing code to redirect only your specific 20 products to their corresponding mirror pages instead of sending every product to Google. This approach is simple to maintain, even if you're new to WooCommerce development:
Step 1: Use a Mapping Array for Easy Management
Instead of writing a bunch of if statements for each product, we'll create a key-value array where each key is your product ID (or slug) and the value is the mirror page URL. This makes it super easy to add/remove products later without messing with conditional logic.
Modified Code
add_action('template_redirect','custom_specific_product_redirect'); function custom_specific_product_redirect(){ // Exit early if WooCommerce isn't active if (!class_exists('WooCommerce')) { return; } // Only run on single product pages if (!is_product()) { return; } // Get the current product's ID (you can use slug instead if preferred) $current_product_id = get_the_ID(); // Define your product-to-mirror URL mapping here // Replace the IDs and URLs with your actual product data $product_redirects = array( 123 => 'https://your-mirror-site.com/product-1', 456 => 'https://your-mirror-site.com/product-2', 789 => 'https://your-mirror-site.com/product-3', // Add all 20 of your products here... ); // Check if the current product is in our redirect list if (isset($product_redirects[$current_product_id])) { // Use 301 for permanent redirect (best for SEO) or 302 for temporary wp_redirect($product_redirects[$current_product_id], 301); exit(); // Always exit after redirect to stop further code execution } }
Key Details & Tips
- Finding Product IDs: To get a product's ID, go to your WooCommerce Products list. Hover over a product title, and you'll see the ID in the browser's status bar. Or when editing a product, look at the URL bar—you'll see
post=123where 123 is the ID. - Using Slugs Instead of IDs: If you prefer using product slugs (the URL-friendly name of the product), replace
$current_product_id = get_the_ID();with$current_product_slug = get_post()->post_name;and update the array keys to match your product slugs (e.g.,'blue-t-shirt' => 'https://mirror-site.com/blue-t-shirt'). - Redirect Type:
301is a permanent redirect, which tells search engines the product has moved permanently—great for preserving SEO. Use302if this is a temporary redirect. - Maintainability: Adding or removing products only requires updating the
$product_redirectsarray, no need to rewrite conditional checks.
If you ever need to scale beyond 20 products, you could use custom product fields to store the mirror URL directly in each product's edit screen, but for 20 items, this array method is the simplest and most straightforward.
内容的提问来源于stack exchange,提问作者Charles Bushwitz

