Images – WP query searches for attachments and their exact title

try something like

Vice versa: https://wordpress.stackexchange.com/a/209714/180599

<?php
global $wpdb;

//The reverse of this: https://wordpress.stackexchange.com/a/209714/180599
$supported_mimes = array( 'image/jpeg', 'image/gif', 'image/png', 'image/bmp', 'image/tiff', 'image/x-icon' );
$all_mimes = get_allowed_mime_types();
$accepted_mimes = array_diff($supported_mimes, $all_mimes);

//and...
$keyword = stripslashes($_REQUEST['keyword']);
//$search = $wpdb->get_col( $wpdb->prepare( " SELECT DISTINCT ID FROM {$wpdb->posts} WHERE post_title="%s" OR post_content="%s" ", $keyword, $keyword ) );
$search = $wpdb->get_col( $wpdb->prepare( " SELECT DISTINCT ID FROM {$wpdb->posts} WHERE post_title="%s" ", $keyword ) );
$query = array(
    'post_type' => 'attachment', 
    'post_status' => 'inherit',
    'orderby' => 'date', 
    'order' => 'DESC',
    'posts_per_page' => 10,
    'post_mime_type' => $accepted_mimes,
    'post__in' => $search,
);  
$attachments = new WP_Query($query);
while($attachments->have_posts()):
    $attachments->the_post();

    echo $attachment->post_content.'<br>';
    echo $attachment->post_title.'<br>';
    //echo wp_get_attachment_image_src($attachment->ID, 'medium', true )[0].'<hr>';
    echo wp_get_attachment_url($attachment->ID).'<hr>';

endwhile;
?>

Leave a Comment