【问题标题】:retrieve single custom field of custom post type检索自定义帖子类型的单个自定义字段
【发布时间】:2013-09-25 20:35:35
【问题描述】:

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

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

【问题讨论】:

  • 在第二个例子中,你为什么不用WP_Query 呢?
  • 啊,是的,我应该。我已经更新了它,但我仍然没有收到单个帖子 - 它显示了所有帖子。

标签: wordpress


【解决方案1】:

很遗憾,您不能在 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');

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

【讨论】:

    【解决方案2】:

    我现在找到了解决方案:

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

    按“图像”过滤如我所愿。

    【讨论】:

      猜你喜欢
      • 2011-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-10
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多