Short /go/ Links for Affiliate and Partner URLs
Creates short links such as /go/amazon/ that redirect to long affiliate or partner URLs, so links in posts stay tidy and you can update a destination in one place.
Opens WPIDE on
Code
// Prefix of your short links: /go/amazon/ and so on.
$wpide_go_prefix = 'go';
// Short name => destination. Empty = off. Examples:
// 'amazon' => 'https://www.amazon.com/dp/B000000000?tag=yourtag-20',
// 'hosting' => 'https://partner.example.com/?ref=you',
$wpide_go_links = array();
add_action( 'template_redirect', function () use ( $wpide_go_prefix, $wpide_go_links ) {
// Only when no real page uses the address.
if ( ! $wpide_go_links || ! is_404() ) {
return;
}
$path = isset( $_SERVER['REQUEST_URI'] ) ? (string) wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH ) : '';
$base = (string) wp_parse_url( home_url( '/' . trim( $wpide_go_prefix, '/' ) . '/' ), PHP_URL_PATH );
if ( 0 !== stripos( $path, $base ) ) {
return;
}
$slug = strtolower( trim( substr( $path, strlen( $base ) ), '/' ) );
if ( '' === $slug || empty( $wpide_go_links[ $slug ] ) ) {
return;
}
nocache_headers();
header( 'X-Robots-Tag: noindex, nofollow' );
// 307 is temporary: browsers and search engines do not remember it, so you can change destinations any time.
wp_redirect( esc_url_raw( $wpide_go_links[ $slug ] ), 307 ); // phpcs:ignore WordPress.Security.SafeRedirect -- destinations set by the site owner.
exit;
}, 1 );
// Ask search engines not to crawl the short links.
add_filter( 'robots_txt', function ( $output, $public ) use ( $wpide_go_prefix, $wpide_go_links ) {
if ( ! $public || ! $wpide_go_links ) {
return $output;
}
$path = (string) wp_parse_url( home_url( '/' . trim( $wpide_go_prefix, '/' ) . '/' ), PHP_URL_PATH );
return $output . "\nUser-agent: *\nDisallow: " . $path . "\n";
}, 10, 2 );
Notes
Uses temporary 307 redirects with noindex and a robots.txt rule; real pages at the same address always win.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.