Last active
August 29, 2015 14:21
-
-
Save schutzsmith/2d0ea341486af3e545b2 to your computer and use it in GitHub Desktop.
Change Permalink Based on Custom Field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Author
schutzsmith
commented
May 25, 2015
- 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