Don Rhummy
Don Rhummy

Reputation: 25820

How get attachment id from its title in Wordpress?

This does not work:

$args = array( 
    "post_per_page" => 1,
    "post_type" => "attachment", 
    "post_title" => trim( "My Attachment" )
);

//This is empty
$get_posts = new WP_Query( $args );

I know that attachment exists with that post title because searching by id returns an object with post_title = "My Attachment".

How can I find an attachment by its post title?

Upvotes: 0

Views: 1720

Answers (1)

Gabriel Intriago
Gabriel Intriago

Reputation: 149

sorry for the delay ... You can use a direct query to the class WPDB..

global $wpdb;
$str= "My Attachment";
$posts = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE post_title = '$str' ", OBJECT ); 
if ( $posts ){
    foreach ( $posts as $post ){
        echo $post->post_title;
    }
}

But beware! protects your code from SQL Injection Attacks read more in http://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks

Upvotes: 2

Related Questions