apply_filters () y the_excerpt están dando resultados inesperados

10

Siento que debo estar perdiendo algo bastante obvio, aquí, pero parece que WordPress no puede cooperar.

Estoy generando etiquetas de Facebook OG con una función. Todo funciona bien, excepto por el extracto.

Desde la desaprobación de get_the_excerpt($post->ID) , ¿hay otra forma de crear un extracto sin tener que crear un bucle completamente nuevo? Me parece excesivo.

Mi primer instinto fue usar apply_filters() :

$description = apply_filters('the_excerpt', get_post($post->ID)->post_content);

Eso me da la publicación completa, completa con contenido en formato HTML. Está bien, debe estar equivocado. Así que probé la siguiente idea lógica:

$description = apply_filters('get_the_excerpt', get_post($post->ID)->post_content);

No hay dados. Ahora no hay HTML, pero sigue siendo la publicación completa (lo que es realmente confuso).

Está bien, no hay problema. Vamos a omitir todas las cosas de lujo y solo vamos a la entrada recortada:

$description = wp_trim_excerpt(get_post($post->ID)->post_content);

Sin cambios.

Entonces, mi pregunta es esta: ¿qué diablos está pasando? ¿Hay algo que me esté perdiendo, aquí?

Me metí en el núcleo de WP para encontrar cómo funciona the_excerpt() , y parece ser idéntico a mi llamada:

/**
 * Display the post excerpt.
 *
 * @since 0.71
 * @uses apply_filters() Calls 'the_excerpt' hook on post excerpt.
 */
function the_excerpt() {
    echo apply_filters('the_excerpt', get_the_excerpt());
}

Tengo algunas preguntas basadas en mis hallazgos:

  1. ¿Por qué no se aplica el filtro como se esperaba?
  2. ¿Hay una manera de obtener el extracto fuera del bucle sin crear un nuevo bucle?
  3. ¿Estoy loco?

Gracias de antemano por echar un vistazo. Estoy bastante perplejo, aquí.

    
pregunta jlengstorf 31.12.2011 - 18:23

3 respuestas

15

Resulta que la respuesta estaba en wp_trim_excerpt() .

Está definido en wp-includes/functions.php:1879 :

/**
 * Generates an excerpt from the content, if needed.
 *
 * The excerpt word amount will be 55 words and if the amount is greater than
 * that, then the string ' [...]' will be appended to the excerpt. If the string
 * is less than 55 words, then the content will be returned as is.
 *
 * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
 * The ' [...]' string can be modified by plugins/themes using the excerpt_more filter
 *
 * @since 1.5.0
 *
 * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
 * @return string The excerpt.
 */
function wp_trim_excerpt($text = '') {
    $raw_excerpt = $text;
    if ( '' == $text ) {
        $text = get_the_content('');

        $text = strip_shortcodes( $text );

        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]>', $text);
        $excerpt_length = apply_filters('excerpt_length', 55);
        $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
        $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
    }
    return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
}

Por lo tanto, cualquier texto pasado no se procesa; solo funciona si se llama con un parámetro vacío.

Para resolver esto, agregué un filtro rápido a mi tema que resuelve el problema:

/**
 * Allows for excerpt generation outside the loop.
 * 
 * @param string $text  The text to be trimmed
 * @return string       The trimmed text
 */
function rw_trim_excerpt( $text='' )
{
    $text = strip_shortcodes( $text );
    $text = apply_filters('the_content', $text);
    $text = str_replace(']]>', ']]>', $text);
    $excerpt_length = apply_filters('excerpt_length', 55);
    $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
    return wp_trim_words( $text, $excerpt_length, $excerpt_more );
}
add_filter('wp_trim_excerpt', 'rw_trim_excerpt');

Es algo redundante, pero me gusta más que abrir nuevos bucles cada vez que quiero generar un extracto.

    
respondido por el jlengstorf 01.01.2012 - 19:12
1

Prueba:

   get_post($post->ID)->post_excerpt
                        ^^^^^^^^^^^^

Consulte: get_post Codex para todos los disponibles miembros de retorno.

    
respondido por el hakre 31.12.2011 - 19:09
0

Puede usar mi función personalizada para filtrar el contenido (es de NARGA Framework )

  • Si la publicación tiene un extracto personalizado, muestre en su lugar el contenido
  • Extracto de generación automática del contenido si la publicación no tiene un certificado personalizado
  • Código corto de recorte automático, código HTML, eliminar, [...] agregar texto "Leer más" (traducible)

        /**
        * Auto generate excerpt from content if the post hasn't custom excerpt
        * @from NARGA Framework - http://www.narga.net/narga-core
        * @param $excerpt_lenght  The maximium words of excerpt generating from content
        * @coder: Nguyễn Đình Quân a.k.a Narga - http://www.narga.net
        **/  
        function narga_excerpts($content = false) {
        # If is the home page, an archive, or search results
        if(is_front_page() || is_archive() || is_search()) :
            global $post;
        $content = $post->post_excerpt;
        $content = strip_shortcodes($content);
        $content = str_replace(']]>', ']]>', $content);
        $content = strip_tags($content);
        # If an excerpt is set in the Optional Excerpt box
        if($content) :
            $content = apply_filters('the_excerpt', $content);
        # If no excerpt is set
        else :
            $content = $post->post_content;
            $excerpt_length = 50;
            $words = explode(' ', $content, $excerpt_length + 1);
        if(count($words) > $excerpt_length) :
            array_pop($words);
            array_push($words, '...<p><a class="more-link" href="' . get_permalink() . '" title="' . the_title_attribute('echo=0') . '">  ' . __( 'Read more &#187;', 'narga' ) . ' </a></p>');
            $content = implode(' ', $words);
        endif;
        $content = '<p>' . $content . '</p>';
        endif;
        endif;
        # Make sure to return the content
        return $content;
        }
        // Add filter to the_content
        add_filter('the_content', 'narga_excerpts');
    
respondido por el Narga 15.05.2013 - 15:49

Lea otras preguntas en las etiquetas