Wordpress 检索自定义帖子类型的单个自定义字段

Wordpress 检索自定义帖子类型的单个自定义字段,wordpress,Wordpress,我有一个自定义帖子类型,其中包含一个使用高级自定义字段创建的自定义字段。我可以检索此类型的所有帖子,并使用以下代码显示图像: <?php $args = array( 'post_type' => 'image' ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); ?> <?php $image = get_field('image_file'

我有一个自定义帖子类型,其中包含一个使用高级自定义字段创建的自定义字段。我可以检索此类型的所有帖子,并使用以下代码显示图像:

<?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; ?>

不幸的是,您不能使用X_posts表列名称作为WP_查询类中的参数来筛选数据库帖子

唯一的解决方案是使用posts\u 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');

注意:上述示例是一般性的,您必须应用额外的代码,以便仅在自定义日志记录中严格过滤。上述代码也会影响其他帖子类型查询。

我现在找到了解决方案:

<?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; ?>

" />

按“图像”进行过滤的效果正如我所希望的那样。

在第二个示例中,为什么不再次使用WP\u查询?啊,是的,我应该这样做。我已经更新了它,但我仍然没有收到一篇帖子-它会显示所有帖子。
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');
<?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; ?>