function set_featured_image_from_content( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( wp_is_post_revision( $post_id ) ) return;
if ( has_post_thumbnail( $post_id ) ) return;
$content = get_post_field( 'post_content', $post_id );
if ( ! $content ) return;
$image_id = null;
// Cerca immagini nel blocco galleria
if ( preg_match_all( '/"id":(\d+)/', $content, $gallery_matches ) ) {
foreach ( $gallery_matches[1] as $id ) {
if ( wp_attachment_is_image( $id ) ) {
$image_id = $id;
break;
}
}
}
// Se non trovata in galleria, cerca immagini singole nel contenuto
if ( ! $image_id ) {
if ( preg_match_all( '/
]+wp-image-(\d+)[^>]*>/i', $content, $img_matches ) ) {
foreach ( $img_matches[1] as $id ) {
if ( wp_attachment_is_image( $id ) ) {
$image_id = $id;
break;
}
}
}
}
// Se non trovata, cerca per URL
if ( ! $image_id ) {
if ( preg_match_all( '/
]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $content, $url_matches ) ) {
foreach ( $url_matches[1] as $url ) {
$id = attachment_url_to_postid( $url );
if ( $id ) {
$image_id = $id;
break;
}
}
}
}
// Se trovata imposta come immagine in evidenza
if ( $image_id ) {
set_post_thumbnail( $post_id, $image_id );
return;
}
// Fallback casuale
$fallback_ids = array( 45835, 45834, 45833, 45831, 45832 );
$random_id = $fallback_ids[ array_rand( $fallback_ids ) ];
set_post_thumbnail( $post_id, $random_id );
}
add_action( 'save_post_post', 'set_featured_image_from_content', 10, 1 );
Skip to content
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Batterie Derby del Trotto.