feat: Affiliate program enrichment (Link Builder, Curated Collections, Smart Links)
This commit is contained in:
83
includes/Frontend/SmartRotator.php
Normal file
83
includes/Frontend/SmartRotator.php
Normal file
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace WooNooW\Frontend;
|
||||
|
||||
if (!defined('ABSPATH')) exit;
|
||||
|
||||
class SmartRotator
|
||||
{
|
||||
public static function init()
|
||||
{
|
||||
add_action('init', [__CLASS__, 'register_rewrite_rules']);
|
||||
add_filter('query_vars', [__CLASS__, 'register_query_vars']);
|
||||
add_action('template_redirect', [__CLASS__, 'handle_redirect']);
|
||||
}
|
||||
|
||||
public static function register_rewrite_rules()
|
||||
{
|
||||
// Match /go/collection-slug
|
||||
add_rewrite_rule(
|
||||
'^go/([^/]+)/?$',
|
||||
'index.php?woonoow_go_slug=$matches[1]',
|
||||
'top'
|
||||
);
|
||||
}
|
||||
|
||||
public static function register_query_vars($vars)
|
||||
{
|
||||
$vars[] = 'woonoow_go_slug';
|
||||
return $vars;
|
||||
}
|
||||
|
||||
public static function handle_redirect()
|
||||
{
|
||||
$slug = get_query_var('woonoow_go_slug');
|
||||
if (empty($slug)) {
|
||||
return;
|
||||
}
|
||||
|
||||
global $wpdb;
|
||||
$collections_table = $wpdb->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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user