Wordpress-如何显示特定类别的特色图像作为背景


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()中,我设法使它正常工作。现在,它只会获取帖子的特色图像,并将其设置为背景,如果它属于"结果"类别。

但这段代码中有些错误,因为现在我的页面内容都没有出现。禁用该功能,内容返回。

我做错了什么?

[edit]我认为这是我查询类别名称的方式。因为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"语句上设置默认图像

试试看!。。。