0

I am developing a wordpress blog theme and I want to use the heading1 element(tag) from post content to be used as the title for my posts instead of the default title. Actually, I want the title for my posts to be a little longer than the default title(which I require to set shorter for meeting SEO recommendations).

Probably I would need something like <?php get_the_tag(); ?>

instead of <?php the_title(); ?>

2
  • 1
    Where do you want to use the shorter title, and where do you want to use the longer title? You could use WP's native title in some places and a shorter one elsewhere. Many sites use SEO plugins such as Yoast to make the <title> tag different than the WP title.
    – WebElaine
    Commented Feb 15, 2019 at 20:25
  • 1
    A custom field would be a much more sensible option than trying to extract the value from HTML, if you ask me. But I don't really understand what you're trying to do. When you say "title", what are you referring to? The <title> element? The name of the post in the back-end? The meta title? If you're not using the_title() then what are you using the title for that requires it to be shorter? Commented Feb 16, 2019 at 2:49

1 Answer 1

0

You can try extracting the content of the first H1 tag from your post.

function get_first_h1(){

    //Get filtered content of post
    ob_start();
    the_content();
    $content = ob_get_clean();

    //Define matching pattern: content of h1 tags
    $h1_pattern = "~<h1>(.*)</h1>~";

    //Variable to hold results
    $header_matches = array();

    //Search content for pattern
    preg_match( $h1_pattern, $content, $header_matches );

    //First match will be 2nd item in array (first is entire content, if any matches)
    if ( count( $header_matches ) > 1 ){
        return $header_matches[1];
    }

    //Fallback: return post title
    return get_the_title();

}

Notes:

  • That function should be saved in functions.php, a custom plugin, or a file included in one of those
  • Result of that function may be echoed out or used as part of another function , i.e. echo get_first_h1();
  • That function, as written, must be used within a WordPress Loop

Personally, I like @Jacob Peattie's suggestion above better. Create a custom field to store the extra title field you want. I am providing this solution in case you must do it this way, i.e. you have 1,000's of posts and don't want to go set the title fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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