• When I publish a new post and let the title blank I want to push the first sentence of the post content as the post title of my blog automatically.
    How to achieve that?

    Thank you very much !

Viewing 1 replies (of 1 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    With this in your theme’s functions.php you can show a custom field with a key “title” as the title (if there is no title):

    add_filter( 'the_title', 'meta_title', 10, 2 );
    function meta_title( $title, $id ) {
    	if ( trim( $title ) == '' ) {
    		$meta_title = get_post_meta( $id, 'title', true );
    		if ( $meta_title ) {
    			$title = $meta_title;
    		}
    	}
    	return $title;
    }

    Another (less reliable) way is to use a regular expression to try and get all the characters of the post content before the first “.?!” followed by a space.

    add_filter( 'the_title', 'first_sentence', 10, 2 );
    function first_sentence( $title, $id ) {
    	if ( trim( $title ) == '' ) {
    		$post = get_post( $id );
    		if ( isset( $post->post_content ) && $post->post_content ) {
    			if ( preg_match( '/(.*?[?!.](?=\s|$)).*/', $post->post_content ) ) {
    				$title  = preg_replace( '/(.*?[?!.](?=\s|$)).*/', '\\1', $post->post_content );
    
    			}
    		}
    	}
    	return $title;
    }

    Don’t use both code samples at the same time.

Viewing 1 replies (of 1 total)
  • The topic ‘Push the first sentence as the post title’ is closed to new replies.