I'm fiddling around with an issue I cannot solve. Inside the loop I would like to find the URL of an inserted media file (pdf, doc etc) and display this as an anchor. Furthermore I would like to display the title of the current post as content of the link. My attempt so far:
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<a href="<?php wp_get_attachment_url(); ?>"><?php the_title(); ?></a>
<?php endwhile; ?>
<?php endif; ?>
displaying the title works totally fine. But the href=""
does not show up anything. Thanks
Note: It is a media file simply inserted as post content, not a featured image or something.
I'm fiddling around with an issue I cannot solve. Inside the loop I would like to find the URL of an inserted media file (pdf, doc etc) and display this as an anchor. Furthermore I would like to display the title of the current post as content of the link. My attempt so far:
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<a href="<?php wp_get_attachment_url(); ?>"><?php the_title(); ?></a>
<?php endwhile; ?>
<?php endif; ?>
displaying the title works totally fine. But the href=""
does not show up anything. Thanks
Note: It is a media file simply inserted as post content, not a featured image or something.
I took a quick peek at the other question referenced in other comments, and the gist of how you loop through attachments there meshes with what is shown in the wp_get_attachment_image
documentation example. In a nutshell, any attachments on a particular post will reference that post by ID.
In particular, it's crucial to understand that attachments are also posts themselves of the post type attachment. Inside your main loop, you'll get your attachments by running a nested query for all attachments whose post parent is equal to the ID of your outer loop's post:
// Our main (outer) query:
while(have_posts()) {
the_post();
$nested_query = new WP_Query(array(
"post_type" => "attachment",
"post_status" => "inherit",
"posts_per_page" => -1,
"post_parent" => get_the_ID() // attachments belonging to the post we're looking at
));
$attachments = $nested_query->get_posts(); // get an array of post objects for each attachment
foreach($attachments as $att_post) {
printf("<a href='%s'>%s</a>", wp_get_attachment_url($att_post->ID), get_the_title());
}
}
I doubt the above does what you want it to, primarily because I don't think you want to echo an anchor for every single attachment that has the post title for its text. However, for illustrative purposes, this is how you could loop through attachments nested within a post loop.
wp_get_attachment_url()
need the ID of the attachment to output URL which you are not providing and simply adding$id
or$post->id
will not work either because that will be post IDs, not the ID of the attachment(s). You will need a way to find all the attachments of a post & their IDs and then use each IDs inwp_get_attachment_url()
to get URL. – Robert hue Commented Oct 9, 2014 at 9:35