The code you posted is a function definition, and function definitions belong in functions.php
to begin with. Simply move the code to functions.php
, and then call it from wherever you need it in your template files.
If you want a variable image sizes, you simply need to pass an argument to the function. For example:
<?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="https://wordpress.stackexchange.com/questions/26031/<?php echo $img[0] ; ?>" width="<?php echo $img[1] ?>" height="<?php echo $img[2] ?>"/>
<?php }
}
?>
Then, when you call the function, it would look like this:
<?php mytheme_get_attached_images( 'medium' ); ?>
(Note: there are other ways the code could be improved; this just shows you how to use the existing code for your purposes.)