Come rimuovere le immagini visualizzate in un post con the_content()?
Sto cercando di imparare di più sulla creazione dei miei temi personalizzati senza utilizzare plugin. Vorrei avere la possibilità di visualizzare tutte le immagini in un post escludendo la miniatura nel mio file single-foobar.php
e posso farlo con:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
$thumb_ID = get_post_thumbnail_id( $post->ID );
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID,
'exclude' => $thumb_ID
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<div class="portproject">';
$image_res = wp_get_attachment_image( $attachment->ID, ' img-responsive' );
echo $image_res;
echo '</div>';
}
}
else { ?>
<span>Nessuna immagine caricata al momento</span>
<?php } endwhile; endif; ?>
Tuttavia, quando applico il mio HTML statico e poi provo a chiamare get_the_content()
con:
<?php
$content = get_the_content();
$content = preg_replace("/<img[^>]+\>/i", "(image) ", $content);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo $content;
?>
rimuove le immagini ma lascia un (image)
nel post con degli spazi e poi visualizza il testo rimanente. Ho trovato una domanda simile ma suggerisce di utilizzare get_the_content()
che però rimuove tutta la formattazione dal post. Quindi la mia domanda è: come posso rimuovere le immagini da the_content()
? Ho trovato "Ottenere solo il testo da the_content in WordPress (Rimuovere i Tag Immagine)" dalle mie ricerche ma anche quello utilizza l'approccio con get_the_content()
.
Il metodo che preferisco utilizzare è solo leggermente più breve della risposta precedente.
<?php $myExcerpt = wp_trim_words( get_the_content(), 20, '' ) ;
echo $myExcerpt ; ?>
La funzione di WordPress wp_trim_words() restituisce solo testo (nessuna immagine).
wp_trim_words ( string $testo, int $num_parole = 55, string $altro = null )
