prefix . 'woonoow_affiliate_collections'; $affiliates_table = $wpdb->prefix . 'woonoow_affiliates'; // Lookup collection and affiliate in one query $query = $wpdb->prepare( "SELECT c.product_ids, a.referral_code FROM {$collections_table} c JOIN {$affiliates_table} a ON c.affiliate_id = a.id WHERE c.slug = %s LIMIT 1", $slug ); $result = $wpdb->get_row($query); if (!$result || empty($result->product_ids)) { // Fallback: 404 or redirect to shop wp_safe_redirect(site_url('/shop/')); exit; } $product_ids = json_decode($result->product_ids, true); if (!is_array($product_ids) || empty($product_ids)) { wp_safe_redirect(site_url('/shop/')); exit; } // Randomly pick a product $random_product_id = $product_ids[array_rand($product_ids)]; // Get the permalink for the product $target_url = get_permalink($random_product_id); if (!$target_url) { wp_safe_redirect(site_url('/shop/')); exit; } // Append the affiliate referral code $target_url = add_query_arg('ref', $result->referral_code, $target_url); // Redirect to the product page wp_redirect($target_url, 302); exit; } }