代码之家  ›  专栏  ›  技术社区  ›  my notmypt

同一类别中所有帖子的默认缩略图

  •  0
  • my notmypt  · 技术社区  · 8 年前

    我的Wordpress网站使用第一个图像作为帖子缩略图,代码:

    add_filter('the_content','replace_content');
    function get_first_image() {
    global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    $first_img = $matches[1][0];
    
    if(empty($first_img)) {
    $first_img = "/path/to/default.png";
    }
    return $first_img;
    }
    

    我该怎么做?

    3 回复  |  直到 8 年前
        1
  •  0
  •   Paul    8 年前

    您需要首先获取当前帖子类别,然后在代码中生成if语句。

    检查此链接: https://developer.wordpress.org/reference/functions/get_the_category/#comment-305

        2
  •  0
  •   morgyface    8 年前

    这个怎么样,我们用的是 has\u post\u缩略图 为了检查图像附件,如果不存在,我们正在设置图像和图像源。从那里我们检查类别分配,如果没有类别匹配,我们使用默认缩略图。

    <?php
    if ( ! has_post_thumbnail() ) {
        $themefolder = get_bloginfo('template_directory');
        echo '<img src="' . $themefolder . '/images/';
        if ( is_category( 'Category A' ) ) {
            echo 'no-image-a.png';
        } elseif ( is_category( 'Category B' ) ) {
            echo 'no-image-b.png';    
        } else {
            echo 'no-image.png'; 
        }
        echo '" alt="' . get_the_title() . '">' . PHP_EOL;
    }
    ?>
    
        3
  •  0
  •   my notmypt    8 年前

    add_filter('the_content','replace_content');
    function get_first_image() {
    global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    $first_img = $matches[1][0];
    
    if(empty($first_img)) {
      $categories = get_the_category();
    
    if ( ! empty( $categories ) ) {
    foreach ( $categories as $category ) {
    if( $category->name == 'Category A' ){ $first_img = "/path/to/default1.png";}  
    elseif ( $category->name == 'Category B' ){ $first_img = "/path/to/default2.png";}
    else {$first_img = "/path/to/default3.png";}
    }
    }
    }
    return $first_img;
    }