I'm trying to get custom field data into the permalink / URL of a custom post type page.
At the moment I've got...
website.com/customposttype/postname/
..but I would like...
website.com/randomstring/postname/
customposttype = Custom POst type randomstring= custom post meta value random
I'm registering the custom post type in the normal way. I've tried several plugins which either don't work, or, work on the main post page but not on custom post pages. I ran out of talent along time ago!
I tried below code and got solution and now Url works fine but when i try to open other default post and pages then its will show the home page content.
add_action('init', 'wpq_add_rewrite_rules');
add_filter('post_type_link', 'wpq_permalinks', 10, 3);
function wpq_add_rewrite_rules()
{
// Register custom rewrite rules
global $wp_rewrite;
$wp_rewrite->add_rewrite_tag('%POST_TYPE%', '([^/]+)', 'POST_TYPE=');
$wp_rewrite->add_rewrite_tag('%post_custom_data%', '([^/]+)', 'post_custom_data=');
$wp_rewrite->add_permastruct('POST_TYPE', '/%post_custom_data%/%POST_TYPE%', false);
}
function wpq_permalinks($permalink, $post, $leavename)
{
$no_data = 'no-data';
$post_id = $post->ID;
if($post->post_type != 'POST_TYPE' || empty($permalink) || in_array($post->post_status, array('draft', 'pending', 'auto-draft')))
return $permalink;
$data = get_post_meta($post_id, 'permalink_data', true);
if(!$data)
$data = $no_data;
$permalink = str_replace('%post_custom_data%', $data, $permalink);
return $permalink;
}