您发布的代码是函数定义,函数定义属于functions.php
以开始。只需将代码移动到functions.php
, 然后在模板文件中需要的任何位置调用它。
如果需要可变的图像大小,只需将参数传递给函数即可。例如:
<?php
function mytheme_get_attached_images( $size = \'full\' ){
// This function runs in "the_loop", you could run this out of the loop but
// you would need to change this to $post = $valid_post or something other than
// using the global post declaration.
global $post;
$args = array(
\'post_type\' => \'attachment\',
\'numberposts\' => 1,
\'post_status\' => null,
\'post_parent\' => $post->ID,
\'order\' => \'ASC\',
\'orderby\' => \'menu_order\'
);
$attachment = get_posts($args); // Get attachment
if ( $attachment ) {
$img = wp_get_attachment_image_src( $attachment[0]->ID, $size ); ?>
<img alt="<?php the_title(); ?>" src="<?php echo $img[0] ; ?>" width="<?php echo $img[1] ?>" height="<?php echo $img[2] ?>"/>
<?php }
}
?>
然后,当您调用该函数时,它将如下所示:
<?php mytheme_get_attached_images( \'medium\' ); ?>
(注意:还有其他改进代码的方法;这只是向您展示了如何将现有代码用于您的目的。)