Múltiples longitudes de extracto en wordpress


Como se dice en el título, estoy buscando múltiples longitudes de extracto en WordPress.

Entiendo que puedes hacer esto en funciones.php:

function twentyten_excerpt_length( $length ) {
    return 15;
}
add_filter( 'excerpt_length', 'twentyten_excerpt_length' );

Lo que quiero saber es cómo puedes tener múltiples de estos que devuelven diferentes valores numéricos para que pueda obtener extractos cortos para los bucles de la barra lateral, extractos más largos para los bucles destacados y el extracto más largo para el artículo principal.

Algo así como usar estos en las plantillas:

<?php the_excerpt('length-short') ?>
<?php the_excerpt('length-medium') ?>
<?php the_excerpt('length-long') ?>

Saludos, Dave

Author: davebowker, 2010-11-03

15 answers

Qué tal...

function excerpt($limit) {
      $excerpt = explode(' ', get_the_excerpt(), $limit);

      if (count($excerpt) >= $limit) {
          array_pop($excerpt);
          $excerpt = implode(" ", $excerpt) . '...';
      } else {
          $excerpt = implode(" ", $excerpt);
      }

      $excerpt = preg_replace('`\[[^\]]*\]`', '', $excerpt);

      return $excerpt;
}

function content($limit) {
    $content = explode(' ', get_the_content(), $limit);

    if (count($content) >= $limit) {
        array_pop($content);
        $content = implode(" ", $content) . '...';
    } else {
        $content = implode(" ", $content);
    }

    $content = preg_replace('/\[.+\]/','', $content);
    $content = apply_filters('the_content', $content); 
    $content = str_replace(']]>', ']]&gt;', $content);

    return $content;
}

A continuación, en el código de la plantilla que acaba de utilizar..

<?php echo excerpt(25); ?>

De: http://bavotasan.com/tutorials/limiting-the-number-of-words-in-your-excerpt-or-content-in-wordpress/

 90
Author: Marty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-15 17:07:10

Por ahora, puedes actualizar la respuesta de Marty:

function excerpt($limit) {
    return wp_trim_words(get_the_excerpt(), $limit);
}

También puede definir el enlace personalizado 'leer más' de esta manera:

function custom_read_more() {
    return '... <a class="read-more" href="'.get_permalink(get_the_ID()).'">more&nbsp;&raquo;</a>';
}
function excerpt($limit) {
    return wp_trim_words(get_the_excerpt(), $limit, custom_read_more());
}
 64
Author: Michał Rybak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-20 16:43:32

Esto es lo que se me ocurrió.

Añadir esto a su functions.php

class Excerpt {

  // Default length (by WordPress)
  public static $length = 55;

  // So you can call: my_excerpt('short');
  public static $types = array(
      'short' => 25,
      'regular' => 55,
      'long' => 100
    );

  /**
   * Sets the length for the excerpt,
   * then it adds the WP filter
   * And automatically calls the_excerpt();
   *
   * @param string $new_length 
   * @return void
   * @author Baylor Rae'
   */
  public static function length($new_length = 55) {
    Excerpt::$length = $new_length;

    add_filter('excerpt_length', 'Excerpt::new_length');

    Excerpt::output();
  }

  // Tells WP the new length
  public static function new_length() {
    if( isset(Excerpt::$types[Excerpt::$length]) )
      return Excerpt::$types[Excerpt::$length];
    else
      return Excerpt::$length;
  }

  // Echoes out the excerpt
  public static function output() {
    the_excerpt();
  }

}

// An alias to the class
function my_excerpt($length = 55) {
  Excerpt::length($length);
}

Se puede usar así.

my_excerpt('short'); // calls the defined short excerpt length

my_excerpt(40); // 40 chars

Esta es la forma más fácil que conozco de agregar filtros, que se pueden llamar desde una función.

 25
Author: Baylor Rae',
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-02 23:13:36

También estaba buscando esta característica y la mayoría de las funciones aquí son buenas y flexibles. Para mi propio caso, estaba buscando una solución que muestre una longitud de extracto diferente solo en páginas específicas. Estoy usando esto:

function custom_excerpt_length( $length ) {
    return (is_front_page()) ? 15 : 25;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

Pegue este código dentro de las funciones themes.archivo php.

 10
Author: Olaf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-30 13:57:19

Volviendo a la respuesta de Marty:

Sé que ha pasado más de un año desde que se publicó esta respuesta, pero es mejor tarde que nunca. Para que esto funcione con límites de más del predeterminado de WordPress de 55, debe reemplazar esta línea:

     $excerpt = explode(' ', get_the_excerpt(), $limit);

Con esta línea:

     $excerpt = explode(' ', get_the_content(), $limit);

De lo contrario, la función solo funciona con un fragmento de texto ya recortado.

 5
Author: 0x61696f,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-24 11:58:37

Puede agregar a sus funciones.archivo php esta función

function custom_length_excerpt($word_count_limit) {
    $content = wp_strip_all_tags(get_the_content() , true );
    echo wp_trim_words($content, $word_count_limit);
}

Luego llámelo en su plantilla de esta manera

<p><?php custom_length_excerpt(50); ?>

El wp_strip_all_tags debería evitar que las etiquetas html perdidas rompan la página.


Documentación sobre funciones

 5
Author: Mike Grace,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-29 21:51:21

Creo que ahora podemos usar wp_trim_words ver aquí . No estoy seguro de qué datos adicionales de escape y desinfección necesarios para utilizar esta función, pero parece interesante.

 4
Author: Tri Nguyen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-07 03:34:33

Aquí una manera fácil de limitar el contenido o el extracto

$content = get_the_excerpt();
$content = strip_tags($content);    
echo substr($content, 0, 255);

Cambia get_the_excerpt() por get_the_content() si quieres el contenido.

Saludos

 2
Author: Mohammed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-11 09:04:44

Tenga cuidado usando algunos de estos métodos. No todos ellos quitan las etiquetas html, lo que significa que si alguien inserta un enlace a un video (o url) en la primera oración de su publicación, el video (o enlace) aparecerá en el extracto, posiblemente explotando tu página.

 1
Author: Doug Hucker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-15 14:04:57

He encontrado un gran plugin que puede hacer esto { Contenido y Extracto Límite de palabras

 0
Author: Adam Storr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-04 16:27:38

Use Extracto avanzado
http://wordpress.org/extend/plugins/advanced-excerpt / complemento. Yo también encontré una respuesta en esta página.

 0
Author: Hirantha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-23 15:54:31

Lo que es posible crear un código corto, no lo intenté pero escribí para usted la idea principal sobre su estructura

function twentyten_excerpt_length($atts,$length=null){
    shortcode_atts(array('exlength'=>'short'),$atts);

    if(!isset($atts['exlength']) || $atts['exlength'] == 'short') {
        return 15;
    }elseif( $atts['exlength'] == 'medium' ){
        return 30;  // or any value you like
    }elseif( $atts['exlength'] == 'long' ){
        return 45;  // or any value you like
    }else{
        // return nothing
    }
}

add_shortcode('the_excerpt_sc','twentyten_excerpt_length');

Así que puedes usarlo así

[the_excerpt_sc exlength="medium"]
 0
Author: usama sulaiman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-17 11:29:44

Sé que este es un hilo muy antiguo, pero simplemente luché con este problema y ninguna de las soluciones que encontré en línea funcionó correctamente para mí. Por un lado, mi propio filtro "excerpt_more" siempre estaba cortado.

La forma en que lo resolví es horrible, pero es la única solución que pude encontrar. La fealdad implica modificar 4 líneas de WP core(!!) + el uso de otra variable global (aunque WP ya hace esto tanto que no me siento tan mal).

Cambié wp_trim_excerpt en wp-incluye / formateo.php a esto:

<?php
function wp_trim_excerpt($text = '') {
    global $excerpt_length;
    $len = $excerpt_length > 0 ? $excerpt_length : 55;
    $raw_excerpt = $text;
    if ( '' == $text ) {
        $text = get_the_content('');

        $text = strip_shortcodes( $text );

        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]&gt;', $text);
        $excerpt_length = apply_filters('excerpt_length', $len);
        $excerpt_more = apply_filters('excerpt_more', ' ' . '[&hellip;]');
        $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
    }
    $excerpt_length = null;
    return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
}

Lo único nuevo son los bits $excerpt_length y $len.

Ahora, si quiero cambiar la longitud predeterminada, hago esto en mi plantilla:

<?php $excerpt_length = 10; the_excerpt() ?>

Cambiar el núcleo es una solución horrible, así que me encantaría saber si a alguien se le ocurre algo mejor.

 0
Author: powerbuoy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-30 00:19:02

Yo haría lo siguiente:

function _get_excerpt($limit = 100) {
    return has_excerpt() ? get_the_excerpt() : wp_trim_words(strip_shortcodes(get_the_content()),$limit);
}

Uso :

echo _get_excerpt(30); // Inside the loop / query

Por Qué ?

  • If has_excerpt should return given excerpt
  • No, Por lo que recortar palabras / strip shortcodes de the_content
 0
Author: l2aelba,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-30 09:20:20

Aquí es un artículo sobre el uso de longitud de extracto personalizado en WordPres. Hay varias Maneras De Limitar y Controlar la Longitud Del Extracto del Post.

  1. Limite la longitud del extracto del post o la longitud del contenido del post usando el número de palabras.
  2. Limitando la longitud del extracto a un número de caracteres.
  3. Limite el resumen de la publicación agregando la etiqueta 'leer más'.
  4. Habilitar extracto personalizado para escribir su propio resumen para cada post.
  5. Controlar la Longitud del Extracto usando Filtros

Http://smallenvelop.com/limit-post-excerpt-length-in-wordpress / Espero que esto te ayude mucho.

 -1
Author: poonam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-13 06:38:26