[英]How do I query posts custom relationship field and include parsed search term into loop and display results in WordPress
I'm parsing a search term from the URL in a search results page like so:我在搜索结果页面中解析来自 URL 的搜索词,如下所示:
http://localhost:8888/domain/?s=Varilite%20Icon%20Mid&post_type=knowledge_hub
I need the search.php template file to query a ACF relationship custom field to see if the linked post title matches the parsed variable in the URL and display the results.我需要 search.php 模板文件来查询 ACF 关系自定义字段,以查看链接的帖子标题是否与 URL 中的已解析变量匹配并显示结果。 Below is my code but it does not work as it only displays posts with the search term in the post titles.下面是我的代码,但它不起作用,因为它只显示帖子标题中带有搜索词的帖子。 How do I get my query to also check the custom field?如何让我的查询也检查自定义字段? Bare in mind this tempalte file is also used for the default global search so needs to be flexible.请记住,此模板文件也用于默认全局搜索,因此需要灵活。
<?php
$args = array(
'posts_per_page' => -1,
//'fields' => 'ids',
'post_type' => 'knowledge_hub',
'meta_query' => array(
array(
'key' => 'related_products',
'value' => '"'.get_search_query().'"',
'compare' => 'LIKE',
)
),
);
$relatedProductArticles = get_posts($args);
if ( have_posts($relatedProductArticles) ) :
while ( have_posts($relatedProductArticles) ) : the_post($relatedProductArticles);
?>
<article class="col-12 search-item mb-5">
<div class="row d-flex align-items-center">
<div class="col-md-7">
<?php the_post_thumbnail('medium', ['class' => 'w-100']); ?>
</div>
<div class="col-md-4">
<div class="px-4">
<h2><a class="" href="<?php the_permalink() ?>"><?php the_title() ?></a></h2>
<?php the_excerpt(); ?>
</div>
</div>
</div>
</article>
<?php
endwhile;
else : ?>
<h2><?php _e( 'Sorry, no posts matched your criteria.', 'textdomain' );?></h2>
<?php endif;
?>
TRY using $_GET
.尝试使用$_GET
。
<?php
$args = array(
'posts_per_page' => -1,
//'fields' => 'ids',
'post_type' => 'knowledge_hub',
'meta_query' => array(
array(
'key' => 'related_products',
'value' => $_GET['s'],
'compare' => 'LIKE',
)
),
);
$relatedProductArticles = get_posts($args);
if ( have_posts($relatedProductArticles) ) :
while ( have_posts($relatedProductArticles) ) : the_post($relatedProductArticles);
?>
<article class="col-12 search-item mb-5">
<div class="row d-flex align-items-center">
<div class="col-md-7">
<?php the_post_thumbnail('medium', ['class' => 'w-100']); ?>
</div>
<div class="col-md-4">
<div class="px-4">
<h2><a class="" href="<?php the_permalink() ?>"><?php the_title() ?></a></h2>
<?php the_excerpt(); ?>
</div>
</div>
</div>
</article>
<?php
endwhile;
else : ?>
<h2><?php _e( 'Sorry, no posts matched your criteria.', 'textdomain' );?></h2>
<?php endif;
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.