0

I have a custom post type with a custom field created with Advanced Custom Fields. I can retrieve all of the posts of this type and display the images with the following code:

<?php
$args = array( 'post_type' => 'image' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php $image = get_field('image_file'); ?>
<img src="<?php echo $image['url']; ?>" />
<?php endwhile; ?>

However, I want to be able to retrieve a single image url without looping through all of them. How would I go about this?

I've tried this:

<?php
$args = array( 'post_type' => 'image', 'title' => 'Welcome to bird - image 1' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php $image = get_field('image_file'); ?>
<img src="<?php echo $image['url']; ?>" />
<?php endwhile; ?>

But it outputs the entire list - how can I just get a single post? If it helps, the permalink is like this:

/?image=welcome-to-bird-image-1
4

2 回答 2

0

不幸的是,您不能在 WP_Query 类中使​​用 X_posts 表列名称作为参数来过滤数据库帖子。

唯一的解决方案是使用 posts_where 过滤器,然后应用常规 MySQL 代码来过滤帖子。像这样的东西:

function filter_where_title($where = '')
{
    $where .= " OR post_title LIKE '%" . $your_term_here . "%'";                   
    return $where;
}

$posts = new WP_Query();

add_filter('posts_where', 'filter_where_title');

注意:上面的例子是通用的,您必须应用额外的代码才能严格过滤您的自定义帖子记录。上面的代码也会影响其他帖子类型的查询。

于 2013-09-25T12:28:42.473 回答
0

我现在找到了解决方案:

<?php
$args = array( 'post_type' => 'image', 'image' => 'welcome-to-bird-image-3' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php $image = get_field('image_file'); ?>
<img src="<?php echo $image['url']; ?>" />
<?php endwhile; ?>

按“图像”过滤按我的意愿工作。

于 2013-09-25T12:35:35.523 回答