WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to change the slug of a post with a custom field.

In example, if the custom field is "keyword" my post link will become: mysite.com/keyword.

If the custom field is empty, i want to generate a random key like mysite.com/xV5f7A.

How can i do that without change the wordpress core?

Any ideas are welcome! Thanks.

share|improve this question

The slug is saved on the wp_posts while custom fields are on the wp_posts_meta. If you want to make it like that you can use an action hook on save_post that will get the value of the custom fields and saves it as the post slug.

Here is the code

add_action('save_post', 'set_slug');

function set_slug($post_id){
    $new_slug = get_post_meta($post_id,'custom-slug', true);    
    $post_args = array(
        'ID' => $post_id,
        'post_name' => $new_slug,

share|improve this answer
Ok thanks it's clear now. Can you give me an example? – user1568901 Aug 8 '12 at 11:20
Won't this cause an infinite loop? – Stephen Harris Mar 13 '13 at 16:49
I guess you are right. Maybe this is doable with a $wpdb function that skips the save_post hook. – ifdion Mar 14 '13 at 5:33
Make sure to add remove_action('save_post', 'set_slug'); inside the function so it doesn't go into an infinite loop. – Brian Reeves Mar 11 at 15:00

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.