[英]Wordpress - How to display featured image from specific category as background?
首先,PHP不是我的強項,但我們走了。
我在我的functions.php中有一個功能,可以抓取特色圖像並將其設置為背景。 然后在header.php中調用此函數
function set_post_background() {
if(query_posts(array ('category_name' => 'results')));
if (have_posts()) : while (have_posts()) : the_post();
global $post;
$bgimage = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), "Full");
if (!empty($bgimage)) {
return '<style type="text/css">body {background:#fff url('.$bgimage[0].') no-repeat top center;}</style>';
}
endwhile; endif;
wp_reset_query();
}
昨晚,我試圖修改該函數,並將其包裝在query_posts()
我設法讓它正常工作。 它現在只會獲取帖子的精選圖像,如果它位於名為“結果”的類別中,則將其設置為背景。
但是這段代碼中的某些內容是錯誤的,因為現在我的頁面內容都沒有出現。 禁用該功能,內容回來。
我做錯了什么?
[編輯]我認為這是我查詢類別名稱的方式。 因為page.php類似的查詢得到了the_content()
我認為該函數覆蓋了該查詢,因而沒有顯示頁面內容。
問題是你使用的是query_posts
會改變默認主查詢的結果。 這意味着頁面的默認內容將被results
類別中的內容更改。 嘗試這個:
function set_post_background() {
$query = new \WP_Query(['category_name' => 'results']);
if ($query->have_posts()) {
while ($query->have_posts()) : $query->the_post();
$bgimage = wp_get_attachment_image_src(get_post_thumbnail_id($query->post->ID), 'full');
if (!empty($bgimage)) {
return '<style type="text/css">body{background:#fff url('.$bgimage[0].') no-repeat top center}</style>';
}
endwhile;
}
wp_reset_query();
}
在任何情況下, 都不要使用query_posts()
函數來查詢帖子。 參考:
注意 :此函數不適用於插件或主題。 如后面所述,有更好的,更高性能的選項來改變主查詢。 query_posts()是一種過於簡單化和有問題的方法來修改頁面的主要查詢,方法是用新的查詢實例替換它。 它是低效的(重新運行SQL查詢)並且在某些情況下會徹底失敗(特別是在處理帖子分頁時)。
請為您的代碼替換以下代碼,它應該可以正常工作。
function set_post_background() {
$cat_ids=array();
$img='';
$cat_ids=wp_get_post_categories();
foreach($cat_ids as $cat_id){
$img=wpds_tax_pic_url($cat_id);
}
if (!empty($img)) {
return '<style type="text/css">body {background:#fff url('.$img.') no-repeat top center;}</style>';
}}
您還可以在“else”語句中設置默認圖像
試試吧!...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.