以下是將第一個(gè)附件設(shè)置為WordPress中帖子的特色圖片的方法。這對(duì)于“?用戶提交的帖子”很有用,它將“特色圖像”附加到每個(gè)提交的帖子。
在實(shí)施此技術(shù)之前,它有助于發(fā)布一些測(cè)試貼,每個(gè)測(cè)試貼至少具有一個(gè)附加的圖像。另外,請(qǐng)記住在修改任何文件之前進(jìn)行備份。
步驟1:?jiǎn)⒂锰厣珗D像
將以下代碼添加到functions.php:
// 添加特色圖像
add_theme_support('post-thumbnails');
set_post_thumbnail_size(130, 100, true); // 特色圖像的寬、高
該代碼段有兩件事:1)為特色圖片添加主題支持,以及2)為特色圖片設(shè)置合理的尺寸(以前稱為“發(fā)布縮略圖”)。隨時(shí)根據(jù)需要調(diào)整大小。
步驟2:設(shè)定和顯示
有了適當(dāng)?shù)臏y(cè)試帖子并支持特色圖像的主題之后,是時(shí)候?qū)⑺羞@些放到主題single.php文件中了(例如),并將以下代碼放在循環(huán)中的任何位置:
<?php // @ https://wp-mix.com/set-attachment-featured-image/
if (has_post_thumbnail()) {
// 顯示特色圖像
the_post_thumbnail();
} else {
// 設(shè)置特色圖像
$attachments = get_posts(array(
'post_type' => 'attachment',
'post_mime_type'=>'image',
'posts_per_page' => 0,
'post_parent' => $post->ID,
'order'=>'ASC'
));
if ($attachments) {
foreach ($attachments as $attachment) {
set_post_thumbnail($post->ID, $attachment->ID);
break;
}
// 顯示特色圖像
the_post_thumbnail();
}
} ?>
使用以下代碼:如果帖子具有特色圖片,則顯示它,否則我們將第一個(gè)附件設(shè)置為“帖子縮略圖”(又名特色圖片),然后顯示它。請(qǐng)注意,我們正在使用各種相關(guān)的WP函數(shù):
使用食典作為指導(dǎo),可以通過多種方式自定義此技術(shù)。
替代方法
如果您不想把代碼添加到循環(huán)中,可以使用以下替代方法通過functions.php文件設(shè)置特色圖片:
// @ https://wp-mix.com/set-attachment-featured-image/
add_filter('the_content', 'set_featured_image_from_attachment');
function set_featured_image_from_attachment($content) {
global $post;
if (has_post_thumbnail()) {
// 顯示特色圖像
$content = the_post_thumbnail() . $content;
} else {
// 獲取和設(shè)置特色圖像
$attachments = get_children(array(
'post_parent' => $post->ID,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order'
));
if ($attachments) {
foreach ($attachments as $attachment) {
set_post_thumbnail($post->ID, $attachment->ID);
break;
}
// 顯示特色圖像
$content = the_post_thumbnail() . $content;
}
}
return $content;
}
這段代碼基本上與以前的技術(shù)操作方式相同,不同之處在于,我們the_content使用get_children()而不是get_posts()進(jìn)行過濾。根據(jù)需要自定義,玩得開心!
更新!您可能還對(duì)我的技術(shù)感興趣,這些技術(shù)用于顯示帖子中附加的所有圖像以及使用“用戶提交的帖子”顯示圖像。獎(jiǎng)金!:)

