Support » Themes and Templates » Automatic tagging "a-z"

  • Resolved Begin

    (@bentalgad)


    Is it possible in some way to have wordpress adding a tag for the first letter of the post’s title automatically?

    It means:

    If the post is called: “The risen” the post will automatically get the tag “T” when published / saved for the first time?

    Any ideas?

    Thanks

Viewing 6 replies - 1 through 6 (of 6 total)
  • Moderator stephencottontail

    (@stephencottontail)

    You can use wp_set_post_tags() for this.

    You should use a child theme for this change if you aren’t already doing so. If you edit the theme’s functions.php directly, you’ll lose this change if the theme is ever updated to fix security issues or bugs or to add new features. In your child theme’s functions.php, try this code for a base:

    function add_first_letter_as_tag() {
      global $post;
    
      if ( $post && 1 < strlen( $post->post_title ) ) :
        $tag = strtoupper( substr( $post->post_title, 0, 1 ) );
        wp_set_post_tags( $post->ID, $tag, true );
      endif;
    }
    add_action( 'save_post', 'add_first_letter_as_tag' );

    Thanks! But it doesn’t seem to do anything…?!

    Moderator stephencottontail

    (@stephencottontail)

    Are the tags not being applied to the post correctly? If you’re using a child theme, did you remember the opening <?php tag in your functions.php?

    Not being applied at all. i’m using the original theme and not a child theme.

    Moderator stephencottontail

    (@stephencottontail)

    As a quick test, can you try adding the line var_dump( $tag ); to the middle of the function:

    function add_first_letter_as_tag() {
      global $post;
    
      if ( $post && 1 < strlen( $post->post_title ) ) :
        $tag = strtoupper( substr( $post->post_title, 0, 1 ) );
        var_dump( $tag );
        wp_set_post_tags( $post->ID, $tag, true );
      endif;
    }

    Be aware that when you do this, you’ll get the error “headings already sent”. Deleting the var_dump( $tag ); line will resolve that error. Before that, though, you should see text along the lines of string(1) "H". Do you see any text along those lines when you create a new post?

    i found another solution for my issue, but thank you very very very much for the effort!!!

    Thanks!

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Automatic tagging "a-z"’ is closed to new replies.