WP查询循环通过自定义帖子类型在主页上工作,但不在搜索页面上

问题描述:

我有两种自定义帖子类型,称为艺术家绘画。这两种帖子类型均使用高级自定义字段插件创建的名为的艺术家姓名的自定义字段。我需要能够匹配来自这两种帖子类型的自定义字段,以便显示更多信息。WP查询循环通过自定义帖子类型在主页上工作,但不在搜索页面上

仅从查询下面粘贴参数和循环。如果有必要,将会发布更多的代码。

<?php 
$artist_name = get_field('artist'); 

$args = array(
'post_type' => 'artists', 
'meta_value' => $artist_name 
); 
$query_artist = new WP_Query($args); 

if ($query_artist->have_posts()) { 
    while ($query_artist->have_posts()) { 
     $query_artist->the_post(); ?> 
     <p class="artist-name"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p> 
     <?php } 
} else { 
    echo 'Artist not found'; 
} 
wp_reset_postdata(); ?> 

此代码在主页的模板文件中正常工作,但始终在搜索结果页面中打印出“找不到艺术家”。我直接从主页模板复制这些代码,所以拼写错误不是问题。很长一段时间以来,我一直在想这件事。任何人阅读都会对发生的事情有线索吗?

谢谢。

好了,我已经成功地最终得到我想要的工作是什么但我不知道为什么下面的代码工作,我的原来没有,因为他们都是类似的方法来做一个新的查询。

下面的代码,如果其他人有同样的问题:

<?php 
// Permalink for artist 
$artist_name = get_field('artist'); 
global $post; 
$posts = get_posts(array('post_type' => 'artists', 'meta_value' => $artist_name)); 
if($posts): 
    foreach($posts as $post) : 
    setup_postdata($post); ?> 
    <p class="artist-name"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p> 
    <?php endforeach; 
wp_reset_postdata(); 
endif; ?> 
+0

如何获得帖子图片呢? –

我认为wordpress不包括搜索automaticaly自定义类型。

您可以使用插件像https://wordpress.org/plugins/advanced-custom-post-search/或在functions.php中编写自己的函数

function rc_add_cpts_to_search($query) {  
    // Check to verify it's search page 
    if(is_search()) { 
     // Get post types 
     $post_types = get_post_types(array('public' => true, 'exclude_from_search' => false), 'objects'); 
     $searchable_types = array(); 
     // Add available post types 
     if($post_types) { 
      foreach($post_types as $type) { 
       $searchable_types[] = $type->name; 
      } 
     } 
     $query->set('post_type', $searchable_types); 
    } 
    return $query; 
} 
add_action('pre_get_posts', 'rc_add_cpts_to_search'); 

来自实例http://www.remicorson.com/include-all-your-wordpress-custom-post-types-in-search/

+0

嗨。我使用一个名为WP Custom Search的插件来运行这个搜索页面。一直在输出基于搜索的正确内容,但是一旦我将您的代码添加到我的functions.php中,任何和所有搜索查询都会导致“找不到结果”消息。
我希望搜索页面中的结果遍历自定义帖子类型,并从另一个自定义帖子类型的自定义字段中提取值。 – NJT