Consenti HTML in estratto


56

Ecco il mio codice estratto.

// Generate custom excerpt length
function wpbx_excerpt_length($length) {
    return 300;
}
add_filter('excerpt_length', 'wpbx_excerpt_length');

Come posso consentire HTML come <a> <b> <i> <br>

Risposte:


125

GUIDA COMPLETA AGLI ESPERTI

Di recente ho risposto ad alcune domande relative agli estratti, quindi fornirò una spiegazione dettagliata che copra il più possibile.

PREFAZIONE

Sembra che ci siano un paio di domande che sorgono da questa risposta su dove dovrebbe andare il codice, e la risposta è che dipende davvero da te e da come ritieni opportuno. Esistono un paio di opzioni in cui è possibile inserire il codice (se non indicato esplicitamente):

  • Nelle funzioni.php del tuo tema o in qualsiasi file utilizzare come file di funzioni. Ricorda solo quando lo fai, se il tema non è tuo, tutte le modifiche andranno perse quando aggiorni il tema

  • Un modo migliore sarebbe usare il codice in un tema figlio. Come sopra, nel file features.php o relativo alle funzioni

  • Usa il codice in un plugin. Questo è il modo preferito in quanto rende il codice disponibile su tutti i temi. Se cambi tema, non devi preoccuparti di riscrivere lo stesso codice.

Spero che questo chiarisca un po 'le cose :-)

TAG / FORMATTING HTML

the_excerpt()prima di tutto non accetta alcun parametro, quindi non è possibile passargli nulla. È un dato di fatto che the_excerpt()riduce il contenuto a 55 parole e tutti i tag HTML vengono rimossi prima di restituire il testo. the_excerpt()si trova in wp-Includes / post-template.php . Per consentire alcuni o tutti i tag HTML nell'estratto, è necessario creare un nuovo estratto.

Innanzitutto, è necessario rimuovere prima la funzione originale, quindi è necessario agganciare la nuova funzione get_the_excerpt. Si noti che questo nuovo estratto sarà ancora richiamabile come the_excerpt()nei file modello, non è necessario modificarlo. get_the_excerpt()si trova in wp-Includes / post-template.php .

L'estratto utilizza wp_trim_excerptper restituire il testo ritagliato, quindi è necessario rimuovere wp_trim_excerptprima il filtro dell'estratto. wp_trim_excerpt()si trova in wp- Includes / formatting.php , riga 2355. Ecco come:

remove_filter('get_the_excerpt', 'wp_trim_excerpt');

Ora puoi aggiungere il tuo nuovo estratto a get_the_excerpt

add_filter('get_the_excerpt', 'wpse_custom_wp_trim_excerpt');

Per consentire tag / formattazione html, dovremo specificare quali tag dovrai consentire. È possibile utilizzare la seguente strip_tagsdichiarazione per raggiungere questo obiettivo

$wpse_excerpt = strip_tags($wpse_excerpt, wpse_allowedtags());

Il secondo argomento wpse_allowedtags()è una piccola funzione che viene utilizzata per aggiungere i tag the_excerpt()consentirà. Per un elenco completo di tag HTML 5 validi, vai e dai un'occhiata qui . Ecco la funzione, aggiungi eventuali tag html a questo che devi consentire / conservare

function wpse_allowedtags() {
// Add custom tags to this string
    return '<script>,<style>,<br>,<em>,<i>,<ul>,<ol>,<li>,<a>,<p>,<img>,<video>,<audio>'; 
}

Se è necessario consentire tutti i tag HTML, ovvero non rimuovere alcun tag, la strips_tags()funzione può essere omessa / rimossa completamente.

Un punto da notare, tuttavia, quando sono consentiti tag html, questi tag vengono conteggiati come parole, quindi il conteggio delle parole per gli estratti con tag e senza tag non sarà lo stesso. Per correggerlo, dovrai prima rimuovere questi tag dal conteggio delle parole in modo che vengano contate solo le parole.

Ho scritto un estratto che consentirà tutti i tag, contando solo le parole come parole e completerà una frase dopo la quantità di parole impostata (quindi il testo non verrà tagliato a metà frase) e aggiungerò un altro testo dopo l'ultima parola .

Ecco il codice completo

function wpse_allowedtags() {
    // Add custom tags to this string
        return '<script>,<style>,<br>,<em>,<i>,<ul>,<ol>,<li>,<a>,<p>,<img>,<video>,<audio>'; 
    }

if ( ! function_exists( 'wpse_custom_wp_trim_excerpt' ) ) : 

    function wpse_custom_wp_trim_excerpt($wpse_excerpt) {
    $raw_excerpt = $wpse_excerpt;
        if ( '' == $wpse_excerpt ) {

            $wpse_excerpt = get_the_content('');
            $wpse_excerpt = strip_shortcodes( $wpse_excerpt );
            $wpse_excerpt = apply_filters('the_content', $wpse_excerpt);
            $wpse_excerpt = str_replace(']]>', ']]&gt;', $wpse_excerpt);
            $wpse_excerpt = strip_tags($wpse_excerpt, wpse_allowedtags()); /*IF you need to allow just certain tags. Delete if all tags are allowed */

            //Set the excerpt word count and only break after sentence is complete.
                $excerpt_word_count = 75;
                $excerpt_length = apply_filters('excerpt_length', $excerpt_word_count); 
                $tokens = array();
                $excerptOutput = '';
                $count = 0;

                // Divide the string into tokens; HTML tags, or words, followed by any whitespace
                preg_match_all('/(<[^>]+>|[^<>\s]+)\s*/u', $wpse_excerpt, $tokens);

                foreach ($tokens[0] as $token) { 

                    if ($count >= $excerpt_length && preg_match('/[\,\;\?\.\!]\s*$/uS', $token)) { 
                    // Limit reached, continue until , ; ? . or ! occur at the end
                        $excerptOutput .= trim($token);
                        break;
                    }

                    // Add words to complete sentence
                    $count++;

                    // Append what's left of the token
                    $excerptOutput .= $token;
                }

            $wpse_excerpt = trim(force_balance_tags($excerptOutput));

                $excerpt_end = ' <a href="'. esc_url( get_permalink() ) . '">' . '&nbsp;&raquo;&nbsp;' . sprintf(__( 'Read more about: %s &nbsp;&raquo;', 'wpse' ), get_the_title()) . '</a>'; 
                $excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end); 

                //$pos = strrpos($wpse_excerpt, '</');
                //if ($pos !== false)
                // Inside last HTML tag
                //$wpse_excerpt = substr_replace($wpse_excerpt, $excerpt_end, $pos, 0); /* Add read more next to last word */
                //else
                // After the content
                $wpse_excerpt .= $excerpt_more; /*Add read more in new paragraph */

            return $wpse_excerpt;   

        }
        return apply_filters('wpse_custom_wp_trim_excerpt', $wpse_excerpt, $raw_excerpt);
    }

endif; 

remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'wpse_custom_wp_trim_excerpt'); 

Puoi semplicemente rimuovere '//' dalle funzioni di cui hai bisogno in più.

LUNGHEZZA ESTRATTO SU MISURA

A volte è necessario visualizzare semplici estratti di diverse lunghezze e non è possibile scrivere un estratto per ogni post / funzione / pagina. Ecco una simpatica piccola funzione che utilizzawp_trim_words

function wpse_custom_excerpts($limit) {
    return wp_trim_words(get_the_excerpt(), $limit, '<a href="'. esc_url( get_permalink() ) . '">' . '&nbsp;&hellip;' . __( 'Read more &nbsp;&raquo;', 'wpse' ) . '</a>');
}

Ciò che questa piccola funzione fa è prendere get_the_excerpt, ritagliarlo per $limitimpostarlo dall'utente e restituire il testo con un link per saperne di più alla fine.

Puoi chiamare questo estratto come segue nel tuo modello

echo wpse_custom_excerpts($limit);

dove $limitsarà il tuo conteggio delle parole, quindi sarà un estratto di 30 parole

echo wpse_custom_excerpts(30);

Solo una cosa da ricordare qui, se imposti il ​​limite a più di 55 parole, verranno restituite solo 55 parole poiché l'estratto è lungo solo 55 parole. Se sono necessari estratti più lunghi, utilizzare get_the_contentinvece.

LUNGHEZZA ESTRATTO SU MISURA

Se hai solo bisogno di modificare la lunghezza di the_excerpt(), puoi usare la seguente funzione

function wpse_excerpt_length( $length ) {
    return 20;
}
add_filter( 'excerpt_length', 'wpse_excerpt_length', 999 );

Ricorda, dovrai impostare una priorità maggiore di 10 in modo che la tua funzione personalizzata venga eseguita dopo l'impostazione predefinita.

AGGIUNGI LEGGI ALTRO LINK

Tutto il testo restituito dall'estratto ha l'odiato [...]alla fine che non è selezionabile. Per aggiungere un altro testo al posto degli inferi, usa questa funzione

 function wpse_excerpt_more( $more ) {
    return ' <a class="read-more" href="'. get_permalink( get_the_ID() ) . '">' . __('Read More', 'your-text-domain') . '</a>';
}
add_filter( 'excerpt_more', 'wpse_excerpt_more' );

MODIFICARE

Estratto primo paragrafo

Voglio mantenerlo completo, quindi ecco l'estratto che si ritaglia dopo il primo paragrafo.

Ecco una funzione che mantiene intatti i tag HTML, aggiunge un link "Leggi altro" alla fine dell'estratto e ritaglia l'estratto dopo il primo paragrafo.

if ( ! function_exists( 'wpse0001_custom_wp_trim_excerpt' ) ) : 

    function wpse0001_custom_wp_trim_excerpt($wpse0001_excerpt) {
        global $post;
        $raw_excerpt = $wpse0001_excerpt;
        if ( '' == $wpse0001_excerpt ) {

            $wpse0001_excerpt = get_the_content('');
            $wpse0001_excerpt = strip_shortcodes( $wpse0001_excerpt );
            $wpse0001_excerpt = apply_filters('the_content', $wpse0001_excerpt);
            $wpse0001_excerpt = substr( $wpse0001_excerpt, 0, strpos( $wpse0001_excerpt, '</p>' ) + 4 );
            $wpse0001_excerpt = str_replace(']]>', ']]&gt;', $wpse0001_excerpt);

            $excerpt_end = ' <a href="'. esc_url( get_permalink() ) . '">' . '&nbsp;&raquo;&nbsp;' . sprintf(__( 'Read more about: %s &nbsp;&raquo;', 'pietergoosen' ), get_the_title()) . '</a>'; 
            $excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end); 

            //$pos = strrpos($wpse0001_excerpt, '</');
            //if ($pos !== false)
            // Inside last HTML tag
            //$wpse0001_excerpt = substr_replace($wpse0001_excerpt, $excerpt_end, $pos, 0);
            //else
            // After the content
            $wpse0001_excerpt .= $excerpt_more;

            return $wpse0001_excerpt;

        }
        return apply_filters('wpse0001_custom_wp_trim_excerpt', $wpse0001_excerpt, $raw_excerpt);
    }

endif; 

remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'wpse0001_custom_wp_trim_excerpt');

MODIFICA 29-10-2015

Per chiunque abbia bisogno di una soluzione alternativa per non visualizzare il collegamento leggi di più dopo l'estratto quando l'estratto è più breve della quantità di parole impostate, vedere la seguente domanda e risposta


dove function wpse_allowedtags() { // Add custom tags to this string return '<script>,<style>,<br>,<em>,<i>,<ul>,<ol>,<li>,<a>,<p>,<img>,<video>,<audio>'; }
metto

1
Tutto questo codice entra functions.php. Puoi aggiungerlo appena sopra if ( ! function_exists( 'wpse_custom_wp_trim_excerpt' ) ) :nel tuofunctions.php
Pieter Goosen,

1
nvm ho perso la parte superiore del codice
user32447

1
se questo va nel file Functions.php non verrà sovrascritto quando arriva un aggiornamento?
Mcgrailm,

3
@mcgrailm sì, lo sarebbe. Ecco perché è importante aggiungere questo alle funzioni.php dei temi di tuo figlio . Puoi persino aggiungerlo a un plug-in indispensabile
Pieter Goosen,

1

Aggiungi più tag se ne hai bisogno $allowed_tags = ...

function _20170529_excerpt($text) {
$raw_excerpt = $text;
if ( '' == $text ) {
    //Retrieve the post content. 
    $text = get_the_content('');

    //Delete all shortcode tags from the content. 
    $text = strip_shortcodes( $text );

    $text = apply_filters('the_content', $text);
    $text = str_replace(']]>', ']]&gt;', $text);

    $allowed_tags = '<a>,<b>,<br><i>'; 
    $text = strip_tags($text, $allowed_tags);

    $excerpt_word_count = 55; /*** MODIFY THIS. change the excerpt word count to any integer you like.***/
    $excerpt_length = apply_filters('excerpt_length', $excerpt_word_count); 

    $excerpt_end = '[...]'; /*** MODIFY THIS. change the excerpt endind to something else.***/
    $excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end);

    $words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
    if ( count($words) > $excerpt_length ) {
        array_pop($words);
        $text = implode(' ', $words);
        $text = $text . $excerpt_more;
    } else {
        $text = implode(' ', $words);
    }
}
return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
}

Da: http://bacsoftwareconsulting.com/blog/index.php/wordpress-cat/how-to-preserve-html-tags-in-wordpress-excerpt-without-a-plugin/


0

Puoi anche aggiungere un editor di testo avanzato per gli estratti, aggiungere il codice seguente nel file del plugin o nel file function.php del tema e potrai vedere l'editor HTML per gli estratti. Inoltre, renderà estratti anche in formato HTML. #Saluti

L'ho copiato da qualche parte ma non ricordo la fonte. Lo sto usando in tutti i miei progetti e funziona.

inserisci qui la descrizione dell'immagine

/**
  * Replaces the default excerpt editor with TinyMCE.
*/
add_action( 'add_meta_boxes', array ( 'T5_Richtext_Excerpt', 'switch_boxes' ) );
class T5_Richtext_Excerpt
{
    /**
     * Replaces the meta boxes.
     *
     * @return void
     */
    public static function switch_boxes()
    {
        if ( ! post_type_supports( $GLOBALS['post']->post_type, 'excerpt' ) )
        {
            return;
        }

        remove_meta_box(
            'postexcerpt', // ID
            '',            // Screen, empty to support all post types
            'normal'      // Context
        );

        add_meta_box(
            'postexcerpt2',     // Reusing just 'postexcerpt' doesn't work.
            __( 'Excerpt' ),    // Title
            array ( __CLASS__, 'show' ), // Display function
            null,              // Screen, we use all screens with meta boxes.
            'normal',          // Context
            'core',            // Priority
        );
    }

    /**
     * Output for the meta box.
     *
     * @param  object $post
     * @return void
     */
    public static function show( $post )
    {
        ?>
        <label class="screen-reader-text" for="excerpt"><?php
        _e( 'Excerpt' )
        ?></label>
        <?php
            // We use the default name, 'excerpt', so we don’t have to care about
            // saving, other filters etc.
            wp_editor(
                self::unescape( $post->post_excerpt ),
                'excerpt',
                array (
                    'textarea_rows' => 15,
                    'media_buttons' => FALSE,
                    'teeny'         => TRUE,
                    'tinymce'       => TRUE
                )
            );
    }

    /**
     * The excerpt is escaped usually. This breaks the HTML editor.
     *
     * @param  string $str
     * @return string
     */
    public static function unescape( $str )
    {
        return str_replace(
            array ( '&lt;', '&gt;', '&quot;', '&amp;', '&nbsp;', '&amp;nbsp;' ),
                array ( '<',    '>',    '"',      '&',     ' ', ' ' ),
                $str
        );
    }
}
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.