简体   繁体   中英

Wordpress meta in permalink

I have a custom post type called patch . Every patch have a meta key version and the value of this meta is always unique. For example:

  • 1.0.0
  • 1.0.1
  • 1.5
  • ...

I want to make special permalink structure so every patch could be accessible by this URL structure:

www.site.ru/patch/%version%

So www.site.ru/patch/1.0.1 would lead to specific patch post witch meta key version value equals 1.0.1 .

How can I do so?

I guess there should be a way to somehow automaticlly transform %version% to a structure like index.php?p=*needed_patch_post_id* .

Try to use this code:

add_action('init', 'rb_add_rewrite_rules');
add_filter('post_type_link', 'rb_create_permalinks', 10, 3);

function rb_add_rewrite_rules() {
    global $wp_rewrite;
    $wp_rewrite->add_rewrite_tag('%version%', '([^/]+)', 'version=');   
    $wp_rewrite->add_permastruct('patch', 'patch/%version%/', false);
}

function rb_create_permalinks($permalink, $post, $leavename) {

    $no_data = 'no-speciality';

    $post_id = $post->ID;

    if($post->post_type != 'patch' || empty($permalink) || in_array($post->post_status, array('draft', 'pending', 'auto-draft')))

    return $permalink;

    $var1 = get_post_meta($post_id, 'version', true);

    $var1 = sanitize_title($var1);

    if(!$var1) { $var1 = $no_data; }

    $permalink = str_replace('%version%', $var1, $permalink);

    return $permalink;
}

I hope this will work for you. Thanks.

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