How to auto embedded youtube with wp_insert_post()

Youtube urls and other services that embed content in post content work via a feature called oEmbed. You need to use wp_oembed_get() to fetch the embedded content for this to work.

In your case, you’re inserting content directly, so you probably don’t want to just call wp_oembed_get() and call it a day. That won’t work. It’s better to run the functions WordPress has built in to support post content.

apply_filters( 'the_content', $content );

This runs when you output the_content() in your template and includes things like shortcode expansion and oembed discovery. But, it only works if your content is formatted in the right way. You said, “Embeds page on WP Codex says to just put the “video URL into the content area” which is correct with one clarifying point:

Make sure the URL is on its own line and not hyperlinked.

Your insert will look like this:

$new_post = array(
    'post_title'   => $title,
    'post_content' => 'test
    
    https://youtu.be/LPpW_8c5jE4',
    'post_status'  => 'publish',
    'post_author'  => $author,
    'post_type'    => 'post',
);
wp_insert_post( $new_post, true );

Notice the new lines for your post content. This will convert these youtube urls into the appropriate embeds when it’s output in your template.