WP查询搜索附件及其确切标题

时间:2020-01-05 作者:Tim

由于缺乏声誉,我现在必须问这个问题。我想搜索媒体库中的所有图像。只有在搜索图像的确切标题时,才会显示搜索结果。我已经试过了\'exact\' => true 但它不起作用。仍然可以显示类似的图像。我使用以下参数创建了一个查询:

<?php
$args = array(
        \'post_type\' => \'attachment\',
        \'post_mime_type\' => \'image\',
        \'orderby\' => \'post_date\',
        \'order\' => \'desc\',
        \'posts_per_page\' => \'30\',
        \'post_status\'    => \'inherit\',
         );

     $loop = new WP_Query( $args );

while ( $loop->have_posts() ) : $loop->the_post();

$image = wp_get_attachment_image_src( get_the_ID() );
echo "<img src=\'" . $image[0] . "\'>";

endwhile; ?>
希望有人能帮助我。

1 个回复
SO网友:Daniel Gross

试试这样的

与此相反: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;
?>

相关推荐

Woocommerce budget search

我有woo commerce设置。现在的要求就像说,如果我搜索预算,比如说5000,它应该显示总价格为5000的产品(例如一个价格为3000的产品和一个2000奖的产品)。我们该怎么做,请帮忙。