Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.