This piece of code excludes posts from the WordPress search which have the robots meta settings on noindex, following the Yoast SEO settings.
<?php
add_action( 'pre_get_posts', function( \WP_Query $query ) {
if( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
$meta_query = [
'relation' => 'OR',
[
'key' => '_yoast_wpseo_meta-robots-noindex',
'value' => '1',
'compare' => '!=',
],
[
'key' => '_yoast_wpseo_meta-robots-noindex',
'value' => '',
'compare' => 'NOT EXISTS',
]
];
$query->set( 'meta_query', $meta_query );
}
return $query;
});