Thread Starter
Ecko
(@ecko)
New day, clear head/fresh mind. All working. It might not be the best way, perhaps preg_replace() would be suitable? Anyway, if anyone else wants to show a random post image and link it to the post in WordPress. This works:
<?php
$args = array(
'post_type' => 'attachment', // SET POST TYPE
'numberposts' => 5, // SET HOW MANY POSTS TO SHOW
'post_status' => null,
'post_parent' => null, // ANY PARENT
'orderby' => 'rand', // GET RANDOM POSTS
);
$attachments = get_posts($args);
// IF TRUE..
if ($attachments) {
// ... CHURN THROUGH EACH POST ATTACHEMENT AND OUTPUT AS IMAGE LINKED TO POST
foreach ($attachments as $post) {
setup_postdata($post);
// EXPLODE THE PERMALINK AND STRIP DOWN TO JUST THE POST URL
// (POST TYPE IS SET TO ATTACHMENT AND RETURNS http://www.domain.com/post-name/attachment/attachment-name)
$postURL = explode("attachment",get_permalink($post->ID));
// GET THS POST ATTACHMENT IMAGE
$postImage = wp_get_attachment_image($post->ID, $size='thumbnail', $icon = false);
?>
<!-- BREAK OUT OF PHP TO INSERT HTML LINK CODE -->
<a href="<?php echo $postURL[0]; ?>"><?php echo $postImage; ?></a>
<?php
} // END FOREACH LOOP
} // END IF STATEMENT
?>
This is great! Thanks so much for being the only person to answer this question!
However, I am getting a ‘?’ at the end of each url. http://example.com/?
Here’s what I’ve got rolled out:
<?php
$args = array(
'post_type' => 'attachment', // SET POST TYPE
'numberposts' => 5, // SET HOW MANY POSTS TO SHOW
'post_status' => null,
'post_parent' => null, // ANY PARENT
);
$attachments = get_posts($args);
// IF TRUE..
if ($attachments) {
// ... CHURN THROUGH EACH POST ATTACHEMENT AND OUTPUT AS IMAGE LINKED TO POST
foreach ($attachments as $post) {
echo '<div class="box col1">';
setup_postdata($post);
// EXPLODE THE PERMALINK AND STRIP DOWN TO JUST THE POST URL
// (POST TYPE IS SET TO ATTACHMENT AND RETURNS http://www.domain.com/post-name/attachment/attachment-name)
$postURL = explode("attachment",get_permalink($post->ID));
// GET THS POST ATTACHMENT IMAGE
$postImage = wp_get_attachment_image($post->ID, $size='thumbnail', $icon = false);
?>
<!-- BREAK OUT OF PHP TO INSERT HTML LINK CODE -->
<a href="<?php echo $postURL[0]; ?>"><?php echo $postImage; ?></a>
<!-- I added for styling & date -->
<span class="date-image"><?php the_time('m.d'); ?></span>
</div>
<?php
} // END FOREACH LOOP
} // END IF STATEMENT
?>
I basically just added in some HTML & removed orderby, as I want latest post images with links to posts.
Any help would be appreciated!