微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – WordPress – 如何将特定类别的特色图像显示为背景?

首先,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会改变认主查询的结果.这意味着页面内容将被结果类别中的内容更改.试试这个:

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()函数查询帖子.参考:

Note: This function isn’t meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs sql queries) and will outright fail in some circumstances (especially often when dealing with posts pagination).

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐