简体   繁体   中英

Adding slashes to custom Post Type slug in WP

I have a custom Post Type that gets created via XML-RPC, using RubyPress.

When creating the post, I specify some slashes in the post_name (the slug, or permalink)

However, converts those slashes into hyphens:

eg: year/code/some-string-name ends up being year-code-some-string-name

Year and Code are dynamic values so I cannot use the parent-page approach, since each Post will have different values.

After some research, this ended up working for me.

You have to have installed a plugin called Custom Permalinks , as WordPress won't allow you to add slashes in the permalinks via code.

The following code will execute every time a MyPost is up Published. Besides Publish you can use other reserved words, look for "Post Status Transitions" if you're interested.

add_action('publish_mypost', 'add_slashes_to_mypost_slug');

function add_slashes_to_mypost_slug( $post_id ) {
    $post = get_post($post_id);
    $slug = $post->post_name;

    $slug_exploded = explode('-', $slug);
    $year = array_shift($slug_exploded);
    $code = array_shift($slug_exploded);
    $remainder = implode('-', $slug_exploded);
    $new_slug = $year.'/'.$code.'/'.$remainder;

    update_post_meta($post_id, 'custom_permalink', $new_slug);
}

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