Forums

Get attchment by ID or by post_name (3 posts)

  1. DavidPotter
    Member
    Posted 2 years ago #

    I'm writing a plugin to add a shortcut for displaying an image uploaded to your WordPress gallery on any post or page using a shortcode. I'm using the following statement to get attachments:

    $attachments = get_posts('post_type=attachment');

    However, this doesn't work reliably. It doesn't always include the specified attachment, even if the attachment exists in the wp_posts table. What would cause it to exclude some attachments?

    Of course, I'd prefer a query that zeroed in on the specific attachment. Is there a WordPress function I can call to get the attachment I want based on ID or post_name? That would clearly be more performant than what I'm doing. I could go straight to SQL, but I'd prefer not to.

    Thanks,
    David

  2. MichaelH
    Volunteer
    Posted 2 years ago #

  3. DavidPotter
    Member
    Posted 2 years ago #

    The examples on that page didn't work. Here is what ended up working for me:

    $parameters = array(
        'post_type' => 'attachment',
        'post_parent' => null,
        'post_mime_type' => 'image');
    $attachments = get_children($parameters);

    Specifying null for post_parent was the key.

    Thanks for the help.
    David

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags