function ($in) {
$out = array();
$out['token'] = preg_match('/^[0-9a-f]{32}$/', (string) ($in['token'] ?? '')) ? (string) $in['token'] : '';
$out['panel_key'] = preg_match('/^[0-9a-f]{32}$/', (string) ($in['panel_key'] ?? '')) ? (string) $in['panel_key'] : '';
$out['coupon'] = preg_match('/^[A-Z0-9][A-Z0-9_-]{1,24}$/', strtoupper((string) ($in['coupon'] ?? ''))) ? strtoupper((string) $in['coupon']) : '';
$out['feed'] = !empty($in['feed']) ? 1 : 0;
$out['badge_footer'] = !empty($in['badge_footer']) ? 1 : 0;
$out['country'] = preg_match('/^[A-Z]{2}$/', strtoupper((string) ($in['country'] ?? ''))) ? strtoupper((string) $in['country']) : 'GB';
$dmin = isset($in['delivery_min']) && $in['delivery_min'] !== '' ? max(0, min(60, (int) $in['delivery_min'])) : '';
$dmax = isset($in['delivery_max']) && $in['delivery_max'] !== '' ? max(0, min(60, (int) $in['delivery_max'])) : $dmin;
$out['delivery_min'] = $dmin;
$out['delivery_max'] = $dmax;
$out['delivery_working'] = !empty($in['delivery_working']) ? 1 : 0;
return $out;
}));
});
function ctp_settings_page() {
if (!current_user_can('manage_options')) { return; }
$o = get_option(CTP_OPTION, array());
$home = home_url('/');
echo '
Compare The Peptide
';
echo '
Paste the two values your claim gave you at comparethepeptide.org/claim. Nothing here changes where your products rank; the ranking is arithmetic over your own prices.
';
echo '
';
echo '
Status
';
echo '- Token: ' . (ctp_opt('token') !== '' ? 'set, served at ' . esc_html($home) . 'ctp-verify.txt' : 'not set') . '
';
echo '- Panel key: ' . (ctp_opt('panel_key') !== '' ? 'set' : 'not set (orders are not reported)') . '
';
echo '- WooCommerce: ' . (class_exists('WooCommerce') ? 'present' : 'not present (coupon, order reports and feed need it)') . '
';
echo '- Feed: ' . (!empty($o['feed']) && class_exists('WooCommerce') ? '' . esc_html($home) . 'ctp-feed.json' : 'off') . '
';
echo '- Badge: ' . (!empty($o['badge_footer']) ? 'in the footer of every page' : 'not in the footer') . '; the shortcode
[ctp_badge] places it anywhere ';
echo '
';
}
// ---------------------------------------------------------------- the badge (2026-10-17): the shop's live level, served by comparethepeptide.org
function ctp_badge_html() {
$domain = preg_replace('/^www\./', '', (string) parse_url(home_url(), PHP_URL_HOST));
if ($domain === '' || $domain === null) { return ''; }
return ''
. '
';
}
add_shortcode('ctp_badge', function () { return ctp_badge_html(); });
add_action('wp_footer', function () {
if (ctp_opt('badge_footer')) { echo '' . "\n"; }
}, 20);
// ---------------------------------------------------------------- the token: file, dot-file, meta tag
add_action('wp_head', function () {
$t = ctp_opt('token');
if ($t !== '') { echo '' . "\n"; }
}, 1);
add_action('template_redirect', function () {
$path = strtok((string) ($_SERVER['REQUEST_URI'] ?? ''), '?');
$path = '/' . ltrim((string) $path, '/');
if ($path === '/ctp-verify.txt' || $path === '/.well-known/ctp-verify.txt') {
$t = ctp_opt('token');
status_header($t !== '' ? 200 : 404);
header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-cache');
echo $t !== '' ? $t . "\n" : "no token set\n";
exit;
}
if ($path === '/ctp-feed.json') {
ctp_serve_feed();
exit;
}
}, 0);
// ---------------------------------------------------------------- the feed (schema: comparethepeptide.org/ctp-ai/#feed)
function ctp_product_format($name) {
$n = ' ' . strtolower($name);
if (strpos($n, 'lyoprester') !== false) { return 'lyoprester_kit'; }
foreach (array('pre-filled', 'prefilled', 'pre filled', 'liquid') as $w) { if (strpos($n, $w) !== false) { return 'liquid_prefilled'; } }
foreach (array('dual chamber', 'dual-chamber', 'cartridge', ' pen ') as $w) { if (strpos($n . ' ', $w) !== false) { return 'pen_dual_chamber'; } }
if (preg_match('/\b(\d+(?:\.\d+)?)\s?g\b/', $n) && strpos($n, 'vial') === false) { return 'bulk_powder'; }
return 'vial_lyophilised';
}
function ctp_serve_feed() {
$o = get_option(CTP_OPTION, array());
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: max-age=600');
if (empty($o['feed']) || !function_exists('wc_get_products')) {
status_header(404);
echo wp_json_encode(array('error' => 'feed off or WooCommerce absent'));
return;
}
$currency = function_exists('get_woocommerce_currency') ? get_woocommerce_currency() : 'GBP';
$products = wc_get_products(array('status' => 'publish', 'limit' => 500, 'return' => 'objects'));
$rows = array();
foreach ($products as $p) {
if (!$p->is_visible()) { continue; }
$name = html_entity_decode(wp_strip_all_tags($p->get_name()), ENT_QUOTES, 'UTF-8');
$price = (float) wc_get_price_including_tax($p);
if ($price <= 0) { continue; }
$row = array('name' => $name, 'url' => get_permalink($p->get_id()), 'price' => round($price, 2), 'currency' => $currency,
'format' => ctp_product_format($name),
'availability' => $p->is_in_stock() ? ($p->is_on_backorder() ? 'PreOrder' : 'InStock') : 'OutOfStock');
if (preg_match('/(\d+(?:\.\d+)?)\s?mg\b/i', $name, $m)) { $row['quantity_mg'] = (float) $m[1]; }
if (preg_match('/\b(?:pack|box|kit)\s*(?:of)?\s*(\d{1,2})\b|\b(\d{1,2})\s*(?:x|×)\s*\d/i', $name, $m)) { $row['pack_count'] = (int) ($m[1] !== '' ? $m[1] : $m[2]); }
$coa = $p->get_meta('ctp_test_report_url');
if ($coa && preg_match('#^https://#', $coa)) { $row['test_report_url'] = $coa; }
$proc = (string) $p->get_meta('ctp_process');
if ($proc !== '' && array_key_exists($proc, ctp_process_choices())) { $row['process'] = $proc; }
$rows[] = $row;
}
$doc = array('vendor' => get_bloginfo('name'), 'country' => $o['country'] ?? 'GB', 'currency' => $currency,
'generated' => gmdate('Y-m-d\TH:i:s\Z'), 'products' => $rows);
if (isset($o['delivery_min']) && $o['delivery_min'] !== '') {
$doc['delivery_days'] = array('min' => (int) $o['delivery_min'], 'max' => (int) ($o['delivery_max'] !== '' ? $o['delivery_max'] : $o['delivery_min']), 'working_days' => !empty($o['delivery_working']));
}
echo wp_json_encode($doc, JSON_UNESCAPED_SLASHES);
}
// ---------------------------------------------------------------- who made each product (2026-11-15): for a shop that makes
// some products and buys others ready-packed (Mixed); written into the feed as "process", shown on the product as declared
function ctp_process_choices() {
return array('' => 'not stated', 'lyophilise_imported' => 'made and filled by us (raw peptide bought in, lyophilised and filled here)',
'full_chain' => 'synthesised, lyophilised and filled by us', 'fill_imported' => 'dissolved and filled by us as liquid',
'resell_finished' => 'bought in ready-packed');
}
add_action('woocommerce_product_options_general_product_data', function () {
if (!function_exists('woocommerce_wp_select')) { return; }
echo '';
woocommerce_wp_select(array('id' => 'ctp_process', 'label' => 'Compare The Peptide: who made this product', 'options' => ctp_process_choices(),
'desc_tip' => true, 'description' => 'Shown beside this product on Compare The Peptide as your declaration. Leave "not stated" if your whole shop is one kind.'));
echo '
';
});
add_action('woocommerce_admin_process_product_object', function ($product) {
$v = isset($_POST['ctp_process']) ? sanitize_text_field(wp_unslash($_POST['ctp_process'])) : '';
$product->update_meta_data('ctp_process', array_key_exists($v, ctp_process_choices()) ? $v : '');
});
// ---------------------------------------------------------------- the click, the coupon, the order report (as before)
function ctp_click_id_from_request() {
$id = isset($_GET['ctp']) ? (string) $_GET['ctp'] : '';
return preg_match('/^[0-9a-f]{12}$/', $id) ? $id : '';
}
function ctp_click_id_from_cookie() {
$id = isset($_COOKIE['ctp_click']) ? (string) $_COOKIE['ctp_click'] : '';
return preg_match('/^[0-9a-f]{12}$/', $id) ? $id : '';
}
add_action('init', function () {
$id = ctp_click_id_from_request();
if ($id === '' || headers_sent()) { return; }
setcookie('ctp_click', $id, array('expires' => time() + CTP_WINDOW_DAYS * 86400, 'path' => '/', 'secure' => is_ssl(), 'httponly' => false, 'samesite' => 'Lax'));
$_COOKIE['ctp_click'] = $id;
}, 1);
add_action('woocommerce_before_calculate_totals', function ($cart) {
$code = ctp_opt('coupon');
if (is_admin() || $code === '' || empty($_COOKIE['ctp_click'])) { return; }
if (!$cart || $cart->has_discount($code)) { return; }
$cart->apply_coupon($code);
}, 20);
add_action('woocommerce_checkout_order_created', function ($order) {
$id = ctp_click_id_from_cookie();
if ($id === '' || !is_object($order)) { return; }
$order->update_meta_data('_ctp_click', $id);
$order->save();
});
function ctp_report_order($order_id, $status) {
$key = ctp_opt('panel_key');
if (!function_exists('wc_get_order') || $key === '') { return; }
$order = wc_get_order($order_id);
if (!$order) { return; }
$ctp = (string) $order->get_meta('_ctp_click');
if (!preg_match('/^[0-9a-f]{12}$/', $ctp)) { return; }
if ($order->get_meta('_ctp_reported_' . $status)) { return; }
$body = array('key' => $key, 'order_ref' => (string) $order->get_order_number(), 'amount' => (float) $order->get_total(),
'currency' => (string) $order->get_currency(), 'ctp' => $ctp, 'status' => $status);
$r = wp_remote_post(CTP_SALE_URL, array('timeout' => 8, 'headers' => array('Content-Type' => 'application/json'), 'body' => wp_json_encode($body)));
$code = is_wp_error($r) ? 0 : (int) wp_remote_retrieve_response_code($r);
if ($code >= 200 && $code < 300 || $code === 409) {
$order->update_meta_data('_ctp_reported_' . $status, gmdate('c') . ' http ' . $code);
$order->save();
} else {
$order->add_order_note('Compare The Peptide postback failed (http ' . $code . '); it is retried on the next status change.');
}
}
add_action('woocommerce_payment_complete', function ($id) { ctp_report_order($id, 'reported'); });
add_action('woocommerce_order_status_processing', function ($id) { ctp_report_order($id, 'reported'); });
add_action('woocommerce_order_status_completed', function ($id) { ctp_report_order($id, 'reported'); });
add_action('woocommerce_order_status_cancelled', function ($id) { ctp_report_order($id, 'cancelled'); });
add_action('woocommerce_order_status_refunded', function ($id) { ctp_report_order($id, 'cancelled'); });
add_action('woocommerce_thankyou', function ($order_id) {
if (!function_exists('wc_get_order')) { return; }
$order = wc_get_order($order_id);
if (!$order) { return; }
$ctp = (string) $order->get_meta('_ctp_click');
if (!preg_match('/^[0-9a-f]{12}$/', $ctp)) { return; }
$domain = preg_replace('/^www\./', '', (string) parse_url(home_url(), PHP_URL_HOST));
$src = CTP_SALE_URL . '?pixel=1&domain=' . rawurlencode($domain) . '&order_ref=' . rawurlencode((string) $order->get_order_number())
. '&amount=' . rawurlencode((string) $order->get_total()) . '¤cy=' . rawurlencode((string) $order->get_currency()) . '&ctp=' . rawurlencode($ctp);
echo '
';
});