2017-10-09 82 views
0

我的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类使用图片1,在cagory B在使用产品组别的职位...

我怎样才能做到这一点? 谢谢

回答

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

,我想保留它,我不知道如何运用你的代码对于first_image。谢谢 –

+0

你可以替换: 'if(empty($ first_img)){ $ first_img =“/path/to/default.png”; } 回报$ first_img; }' 有: '如果(!空($ first_img)){ 回报$ first_img; } }' 然后在相关页面/帖子模板中独立使用我的代码片段。 – morgyface

+1

谢谢你的男人,搞定! –

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; 
} 
相关问题