This is what I have now within an attachment theme template...

$parsed = parse_url( wp_get_attachment_url( $attachment->ID ) );
$url = dirname( $parsed [ 'path' ] ) . '/' . rawurlencode( basename( $parsed[ 'path' ] ) );

$mtype = get_post_mime_type($attachment->ID); 
$mtypeicon = '';
if ($mtype == "application/pdf") {
    $mtypeicon = "<i class='far fa-file-pdf'></i>";

I'm happy with it. It works. But now, I am in process of moving this code over into my functions.php so I can instead do an add_action/do_action sequence. What is the right way to say $attachment->ID from within a custom function?

Many thanks!


To get the attachment ID, you need to get the post attachments using get_posts() with the post_type being 'attachment' and the post_parent being the ID of the post you're interested in getting the attachments from.

namespace StackExchange\WordPress;
function the_post( \WP_Post $post, \WP_Query $query ) {
  //* Get post attachments
  $attachments = \get_posts( [
    'post_type'      => 'attachment',
    'posts_per_page' => -1,
    'post_parent'    => $post->ID,
    'exclude'        => get_post_thumbnail_id()
  ] );
  //* There can be more than one attachment per post, so loop through them
  foreach( $attachments as $attachment ) {
    //* Maybe do some sanity checks here
    $parsed = parse_url( \wp_get_attachment_url( $attachment->ID ) );
    //* Do something useful with the parsed URL
\add_action( 'the_post', __NAMESPACE__ . '\the_post', 10, 2 );

Above, I'm using the the_post action to get the post ID of the post parent. Depending on your use case, you could use another hook and get_the_ID() to get the ID of the post parent.

| improve this answer | |
  • This worked out perfectly and gave me a first time experience on extracting array data from get_posts(). Many thanks. – klewis May 7 '18 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.