0

Is there any way to generate slug for custom post type in alphabetical order or use first few words from the content of the post?

This is because I have created a custom post type that does not have any title. Only content, categories, etc.

2

You can achieve this using the save_post hook. For example if you have a custom post type stack, the hook can be changed to save_post_stack.

To set the post-slug to the first few words of the content:

add_action( 'save_post_stack', 'wpse251743_set_title', 10, 3 );
function wpse251743_set_title ( $post_id ){
    //This temporarily removes action to prevent infinite loops
    remove_action( 'save_post_stack', 'wpse251743_set_title' );

    $post = get_post( $post_id );

    $post_content = $post->post_content;

    //GET THE FIRST THREE WORDS
    $words = array_slice(str_word_count( $post_content, 2), 0, 5);

    $post_name = implode(' ', $words );

    //update title
    wp_update_post( array(
        'ID'        => $post_id,
        'post_name' =>  $post_name, //Wordpress would generate the slug based on the post name
    ));

    //redo action
    add_action( 'save_post_stack', 'wpse251743_set_title', 10, 3 );
}

Avoiding infinite loops:

If you are calling a function such as wp_update_post that includes the save_post hook, your hooked function will create an infinite loop. To avoid this, unhook your function before calling the function you need, then re-hook it afterward.

  • That did a trick. Cheers.. – Kevin S Jan 8 '17 at 19:21
  • Don't forget to upvote :) – Tunji Jan 8 '17 at 19:21
  • @TunjiAyoola, save_post_... is not a filter but the action hook. Please improve. – prosti Jan 8 '17 at 19:28
  • Do you really need to remove the action add the action @TunjiAyoola inside? I think no. – prosti Jan 8 '17 at 19:35
  • Yes you do: According to the codex; If you are calling a function such as wp_update_post that includes the save_post hook, your hooked function will create an infinite loop. To avoid this, unhook your function before calling the function you need, then re-hook it afterward. – Tunji Jan 8 '17 at 19:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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