Skip Navigation

[Resolved] Redirect each post URL to an exernal URL from a custom field

This thread is resolved. Here is a description of the problem and solution.

Problem: I would like to redirect posts in a specific post type to a URL saved in a custom field on each post.

Solution: Unfortunately Toolset isn't set up to handle redirects so this will require custom code. Here is an example:

function my_cpt_template_redirect()
{
  if( get_post_type() == 'your-cpt-slug' )
  {
    $id = get_the_id();
    $url = get_post_meta( $id, 'wpcf-' . 'your-field-slug', true );
    if( $url ) {
      wp_redirect( $url );
      die;
    }
  }
}
add_action( 'template_redirect', 'my_cpt_template_redirect' );

Replace your-cpt-slug with the slug of the post type where you want to apply these redirects. Replace your-field-slug with the slug of the URL field. Additional changes may be necessary based on your requirements.

Relevant Documentation:
https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect
https://developer.wordpress.org/reference/functions/get_post_meta/

This support ticket is created 6 years, 1 month ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 - -
13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 - -

Supporter timezone: America/New_York (GMT-04:00)

This topic contains 2 replies, has 2 voices.

Last updated by Charles 6 years, 1 month ago.

Assisted by: Christian Cox.

Author
Posts
#1123693

Support,

How can I redirect each post so it gets redirected to an external link provided by a custom field? The custom field I'd like each post redirected to is my "Affiliate Link" field. So essentially single posts are never accessible as long as there is a link provided in the custom field.

Thanks,
Charles

#1123964

Hi, unfortunately Toolset isn't set up to handle redirects so this will require custom code. Here is an example:

function my_cpt_template_redirect()
{
  if( get_post_type() == 'your-cpt-slug' )
  {
    $id = get_the_id();
    $url = get_post_meta( $id, 'wpcf-' . 'your-field-slug', true );
    if( $url ) {
      wp_redirect( $url );
      die;
    }
  }
}
add_action( 'template_redirect', 'my_cpt_template_redirect' );

Replace your-cpt-slug with the slug of the post type where you want to apply these redirects. Replace your-field-slug with the slug of the URL field. Additional changes may be necessary based on your requirements.

#1123968

Solution worked like a charm, Thanks!