加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 16:04:41 所属栏目:PHP教程 来源:网络整理
导读:首先,PHP不是我的强项,但我们走了. 我在我的functions.php中有一个功能,可以抓取特色图像并将其设置为背景.然后在header.php中调用此函数 function set_post_background() { if(query_posts(array ('category_name' = 'results'))); if (have_posts()) : whi
首先,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).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读