This question is about tidying up code and better management of said code butI’m a complete novice when it comes to PHP so would appreciate a little help.
I have this code:
<?php
$thumb_id = get_post_thumbnail_id(get_the_ID()); // gets the post thumbnail ID
$args = array(
'order' => 'ASC',
'orderby' => 'rand',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => 1,
'exclude' => $thumb_id
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
echo wp_get_attachment_image($attachment->ID, 'full', false);
}
}
?>
What it does isn’t important for reference, the above code gets random images from a WordPress post randomly generates one of them in a DIV. I want this functionality across many templates but I don’t want to cram my PHP files with it as my files will get messy and inefficiently large.
2 questions.
- Do I need to change the code above in order to put it within functions.php?
- How can I reference the above code (that will be within my functions.php) using a short one liner that I can reuse across many different templates?
1. You need to get out the
<?phpand?>if you already put your code inside those tagsexample functions.php:
2. Use include(), include_once(), require() or require_once() and save your function in another file, so you can reference that file.
random_img.php
functions.php