以下是將第一個附件設置為WordPress中帖子的特色圖片的方法。這對于“?用戶提交的帖子”很有用,它將“特色圖像”附加到每個提交的帖子。
在實施此技術之前,它有助于發布一些測試貼,每個測試貼至少具有一個附加的圖像。另外,請記住在修改任何文件之前進行備份。
步驟1:啟用特色圖像
將以下代碼添加到functions.php
:
// 添加特色圖像
add_theme_support('post-thumbnails');
set_post_thumbnail_size(130, 100, true); // 特色圖像的寬、高
該代碼段有兩件事:1)為特色圖片添加主題支持,以及2)為特色圖片設置合理的尺寸(以前稱為“發布縮略圖”)。隨時根據需要調整大小。
步驟2:設定和顯示
有了適當的測試帖子并支持特色圖像的主題之后,是時候將所有這些放到主題single.php
文件中了(例如),并將以下代碼放在循環中的任何位置:
<?php // @ https://wp-mix.com/set-attachment-featured-image/
if (has_post_thumbnail()) {
// 顯示特色圖像
the_post_thumbnail();
} else {
// 設置特色圖像
$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();
}
} ?>
使用以下代碼:如果帖子具有特色圖片,則顯示它,否則我們將第一個附件設置為“帖子縮略圖”(又名特色圖片),然后顯示它。請注意,我們正在使用各種相關的WP函數:
使用食典作為指導,可以通過多種方式自定義此技術。
替代方法
如果您不想把代碼添加到循環中,可以使用以下替代方法通過functions.php
文件設置特色圖片:
// @ 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 {
// 獲取和設置特色圖像
$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;
}
這段代碼基本上與以前的技術操作方式相同,不同之處在于,我們the_content
使用get_children()而不是get_posts()進行過濾。根據需要自定義,玩得開心!
更新!您可能還對我的技術感興趣,這些技術用于顯示帖子中附加的所有圖像以及使用“用戶提交的帖子”顯示圖像。獎金!:)