programing

워드프레스의 여러 발췌 길이

nicescript 2023. 3. 8. 23:44
반응형

워드프레스의 여러 발췌 길이

제목에서 알 수 있듯이 워드프레스에서 여러 발췌된 길이를 찾고 있습니다.

함수에서 이 작업을 수행할 수 있다는 것을 알고 있습니다.php:

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

제가 알고 싶은 것은 어떻게 이들 중 여러 개가 다른 수치를 반환할 수 있는지입니다.그러면 사이드바 루프에 대한 짧은 발췌, 피처링 루프에 대한 긴 발췌, 메인 기사에 대한 가장 긴 발췌를 얻을 수 있습니다.

템플릿에서 다음과 같은 것을 사용합니다.

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

건배, 데이브

그럼...

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;
}

템플릿 코드에서는 그냥..

<?php echo excerpt(25); ?>

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

현재 Marty의 응답을 업그레이드할 수 있습니다.

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

커스텀의 「상세 읽기」링크를 다음과 같이 정의할 수도 있습니다.

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());
}

이게 내가 생각해낸 거야.

도 이걸 더해서 쓰세요.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);
}

이렇게 쓸 수 있어요.

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

my_excerpt(40); // 40 chars

이것이 필터를 추가하는 가장 쉬운 방법이며, 하나의 함수로 호출할 수 있습니다.

저도 이 기능을 찾고 있었습니다만, 여기 있는 대부분의 기능은 훌륭하고 유연합니다.제 경우 특정 페이지에서만 발췌 길이가 다른 솔루션을 찾고 있었습니다.이것을 사용하고 있습니다.

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

테마 함수 안에 이 코드를 붙여넣습니다.php 파일.

기능을 추가할 수 있습니다.php 파일 이 함수

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

그럼 템플릿에 이렇게 불러주세요.

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

wp_strip_all_tags을 방지합니다.


기능에 관한 문서

Marty의 답변으로 돌아갑니다.

이 답변이 발표된 지 1년이 훨씬 넘었다는 것을 알지만, 늦더라도 안 하는 것보다는 낫다.WordPress 기본값 55를 초과하는 제한에서 작동하려면 다음 줄을 교체해야 합니다.

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

다음 행과 함께:

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

그렇지 않으면 이 함수는 이미 잘린 텍스트에서만 작동합니다.

★★★★★★★★★를 사용할 수 있을 것 같습니다.wp_trim_words 여기를 봐주세요.이 기능을 사용하기 위해 어떤 추가 데이터 이스케이프 및 삭제가 필요했는지 알 수 없지만 흥미로운 것 같습니다.

콘텐츠 또는 발췌를 제한하는 간단한 방법

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

get_the_content()를 get_the_content()로 변경합니다.

안부 전해요

나는 이렇게 하고 싶다:

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

사용방법:

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

왜요?

  • ifhas_excerpt발췌한 것을 반환해야 한다.
  • 그렇지 않습니다. 단어들/숏코드 제거the_content

나는 짧은 코드를 만드는 것이 가능하다고 생각한다, 나는 그것을 시도하지 않았지만 나는 너를 위해 그것의 구조에 대한 주요 아이디어를 썼다.

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');

이렇게 쓰시면 됩니다.

[the_excerpt_sc exlength="medium"]

이것이 매우 오래된 스레드인 것은 알지만, 저는 이 문제와 씨름하고 있을 뿐이고, 온라인에서 찾은 솔루션 중 어느 것도 제게는 제대로 작동하지 않았습니다.우선, 제 필터는 항상 잘려나갔습니다.

내가 해결한 방법은 형편없지만, 내가 찾을 수 있는 유일한 해결책이야.WP core(!)의 4행 수정과 또 다른 글로벌 변수 사용(WP가 이미 그렇게 많이 하고 있지만, 나는 그렇게 나쁘다고 생각하지 않는다)이러한 문제는 WP core(!)의 4행 수정이 수반됩니다.

나는 변했다wp_trim_excerptwp-syslog/formating으로 지정합니다.php to this:

<?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);
}

유일하게 새로운 것은$excerpt_length그리고.$len비트를 클릭합니다.

기본 길이를 변경하려면 템플릿에서 다음을 수행합니다.

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

핵심을 바꾸는 것은 끔찍한 해결책이기 때문에 누군가 더 나은 방법을 생각해내면 좋겠습니다.

다음 방법 중 몇 가지를 사용할 때 주의하십시오.html 태그를 모두 삭제하는 것은 아닙니다.즉, 누군가가 투고의 첫 번째 문장에 비디오(또는 URL)에 대한 링크를 삽입하면 비디오(또는 링크)가 발췌에 표시되므로 페이지가 폭파될 수 있습니다.

WordPress에서 커스텀 발췌 길이를 사용하는 것에 대한 기사를 썼습니다.발췌한 투고의 길이를 제한 및 제어하는 방법은 여러 가지가 있습니다.

  1. 단어 수를 사용하여 게시물의 발췌 길이 또는 게시물의 내용 길이를 제한합니다.
  2. 발췌 길이를 글자 수로 제한합니다.
  3. '추가 읽기' 태그를 추가하여 게시 요약을 제한합니다.
  4. 커스텀 발췌를 유효하게 하고, 투고 마다 독자적인 요약을 작성합니다.
  5. 필터를 사용한 발췌 길이 제어

이것이 당신에게 많은 도움이 되길 바랍니다.

언급URL : https://stackoverflow.com/questions/4082662/multiple-excerpt-lengths-in-wordpress

반응형