简体   繁体   中英

Add custom field to permalink / URL

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;
}

The way you try to do this is quite hacky. When registering custom post type you have rewrite argument

Where your function call should look something like this:

$args = array(
'labels' => $labels,
    
           'public' => true,
    
           'rewrite' => array('slug' => 'myslug'),
    
           'supports' => array('title', 'editor', 'thumbnail', 'revisions')
);



register_post_type(‘mycustomposttype’, $args);

Note the rewrite parameter, where you can set custom slug of your custom post type.

Also please remember to go to admin panel Settings >> Permalinks and re-save permalink structure, for WordPress to update to new slugs and URL structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM