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

时间:2017-10-09 07:32:27

标签: wordpress thumbnails

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

有些帖子的内容没有图片,所以我想为它们使用不同的默认缩略图:A类中的帖子使用picture1,cagory中的帖子使用category2 ...

我该怎么做? 谢谢

3 个答案:

答案 0 :(得分:0)

您需要先获取当前的帖子类别,然后在代码中创建一个if语句。

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

最后,这是我的代码:

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