Skip to content

Instantly share code, notes, and snippets.

@schutzsmith
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schutzsmith/2d0ea341486af3e545b2 to your computer and use it in GitHub Desktop.
Save schutzsmith/2d0ea341486af3e545b2 to your computer and use it in GitHub Desktop.
Change Permalink Based on Custom Field
add_action('init', 'tdd_add_rewrite_rules');
function tdd_add_rewrite_rules()
{
// Register custom rewrite rules
global $wp_rewrite;
$wp_rewrite->add_rewrite_tag('%your_post_type%', '([^/]+)', 'your_post_type=');
$wp_rewrite->add_rewrite_tag('%your_custom_field%', '([^/]+)', 'your_custom_field=');
$wp_rewrite->add_permastruct('your_post_type', '/%your_custom_field%/%your_post_type%', false);
}
add_filter('post_type_link', 'tdd_permalinks', 10, 3);
function tdd_permalinks($permalink, $post, $leavename)
{
$no_data = 'no-speciality';
$post_id = $post->ID;
if($post->post_type != 'your_post_type' || empty($permalink) || in_array($post->post_status, array('draft', 'pending', 'auto-draft')))
return $permalink;
$var1 = get_post_meta($post_id, 'your_custom_field', true);
$var1 = sanitize_title($var1);
if(!$var1) { $var1 = $no_data; }
$permalink = str_replace('%your_custom_field%', $var1, $permalink);
return $permalink;
}
@schutzsmith
Copy link
Author

  • Add to functions.php inside a WordPress theme
  • Change all instances of your_post_type with the custom post type you want to use.
  • Change all instances of your_custom_field with the field name you want to use.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment