检索单个自定义字段的自定义帖子类型
问题描述:
我有一个自定义帖子类型,其中包含使用高级自定义字段创建的自定义字段。我可以检索所有这类的帖子,并用下面的代码显示图像:检索单个自定义字段的自定义帖子类型
<?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; ?>
不过,我希望能够检索单个图像的URL,而无需通过所有这些循环。我将如何去做这件事?
我已经试过这样:
<?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; ?>
但它输出的整个列表 - 我如何才能得到一个帖子?如果有帮助,对固定链接是这样的:
/?image=welcome-to-bird-image-1
答
我现在已经找到了解决办法:
<?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; ?>
过滤由“形象”的工作,因为我想要的。
答
可惜你不能使用X_posts表列名作为WP_Query类的参数,以过滤数据库的帖子。
唯一的解决方案是使用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');
注:上面的例子是通用的,你必须为了申请额外的代码进行严格筛选只有您的自定义后的记录。上面的代码也会影响其他帖子类型的查询。
在第二个示例中,为什么不再使用WP_Query? –
啊,是的,我应该。我已经更新了它,但我仍然没有收到单个帖子 - 它显示了所有这些帖子。 – babbaggeii