Set post title based on first h2 element in the content section

I have a front end editor set up for users to create posts and I would like to make it as simple as possible to create posts with the least amount of fields involved. Is it possible to generate the post title based on the first h2 element that appears in the content field? How would I do this?

Solutions Collecting From Web of "Set post title based on first h2 element in the content section"

If you can handle this in the PHP side, you might be able to pull the h2 tags from the content using regular expression.

PHP VERSION

Test content

$content = "<h2>This is H2 Content</h2><p>This is p content</p>Random Content<h2>This is another H2 section</h2><b><h2>This the third H2 section</h2></b>";

Grab any text inside H2s

preg_match_all('#<h2>(.*?)</h2>#', $content, $matches);

// Merge the first 2 matches

$potential_title = implode ( ' - ', array_slice($matches[0], 0, 2));

If we have something…

if( ! empty ( $potential_title ) ) {

Remove any HTML from the remaining content

    $cleaner_title = strip_tags( $potential_title );

Prep the post title update

    $my_post_updates = array(
        'ID'           => $post_id,
        'post_title'   => $cleaner_title, 
    );

    // Update the post into the database

    wp_update_post( $my_post_updates );
}

JS VERSION

The Javascript version of this is similar, you would just be required to intercept the form submission, grab the content, parse the results then pass the data along.

This just alerts the result of parsing test content.

// test content    
var content = "<h2>This is H2 Content</h2><p>This is PPP content</p>Random Content<h2>This is another H2 section</h2><b><h2>This the third H2 section</h2></b>";

// variables to store regEx results. 
var match, regex = /<h2>(.*?)<\/h2>/ig, matches = [];

// get all the matches and put in array
while (match = regex.exec(content)) { matches.push( match[1] ); }

// if we have any...
if( matches.length ) {

   // pull the first 2 and join them together
   var title = matches.slice ( 0, 2 ).join ( ' - ' );

   // send this along with your form submission
   alert(title);
}