我正在使用一个站点范围的函数将css添加到<head>
的页面拉入各种特征图像作为响应页面背景。它在我的站点的其他部分都非常有效,但在我使用自定义帖子类型调用帖子的页面上失败WP_Query
. 我想这是因为WP_Query
不使用标准循环,我的函数使用global $post;
.
有没有办法适应WP_Query
循环以使用函数?我需要的特色图像功能,也工作在我的网站,它使用标准的WP循环的其余部分。
--
以下是我如何称呼自定义帖子:
<?php $port_query = new WP_Query( array(
\'post_type\' => \'portfolio\',
\'posts_per_page\' => 1,
\'orderby\' => \'rand\'
) );
if ( $port_query->have_posts() ): while ( $port_query->have_posts() ) : $port_query->the_post(); ?>
<div class="page-bkg responsive-bkg">
// page content here
</div>
<?php endwhile; wp_reset_postdata(); endif;
以及从函数调用响应性特征图像的函数。php:
function bkg_featured_image() {
// call the global post variable
global $post;
if ( has_post_thumbnail( $post->ID ) ) : // checks whether the post has the featured image set
// get the post thumbnail ID for the page or post
$post_thumbnail_id = get_post_thumbnail_id( $post->ID );
// store the image sizes in an array. You can also add your own image sizes with the add_image_size function
$img_sizes = array( \'thumbnail\', \'medium\', \'large\', \'full\', \'thumb480\', \'thumb768\', \'thumb1280\', \'thumb1680\', \'thumb2048\' );
// grab the URL for each image size and store in a variable
foreach ( $img_sizes as $img_size ) {
${ \'img_src_\' . $img_size } = wp_get_attachment_image_src( $post_thumbnail_id, $img_size );
}
echo \'<style type="text/css">
.responsive-bkg {
background-image: url(\' . esc_url( $img_src_thumb768[0] ) . \');
}
@media screen and ( min-width: 768px ) {
.responsive-bkg {
background-image: url(\' . esc_url( $img_src_thumb1280[0] ) . \');
}
}
@media screen and ( min-width: 1281px ) {
.responsive-bkg {
background-image: url(\' . esc_url( $img_src_thumb2048[0] ) . \');
}
}
</style>\';
endif; // end if the featured image is set
} // end function my_featured_image
add_action( \'wp_head\', \'bkg_featured_image\' );
// (this function borrowed from http://s2webpress.com/responsive-featured-image-function-in-wordpress-themes/)