是否可以获得搜索字符串匹配的 ACF 字段名称/ID?ACF 字段也包含在 wordpress 的默认搜索功能中。因此,当搜索字符串与 ACF 字段值匹配时,我还想识别字段名称/ID。那可能吗?
问问题
360 次
2 回答
0
你可以试试这个代码脚本。我希望这对你有用。
$fields = get_fields(get_the_ID());
$acfField = array();
$search_query = get_search_query();
foreach( $fields as $name => $value ):
if($search_query == $value){
$acfField['name'] = $name;
$acfField['value'] =
$value; break;
}
endforeach;
print_r($acfField);
把它放在 as 的循环中search.php
:
while ( have_posts() ) : the_post();
$fields = get_fields(get_the_ID());
$acfField = array();
$search_query = get_search_query();
foreach( $fields as $name => $value ):
if($search_query == $value){
$acfField['name'] = $name;
$acfField['value'] = $value;
break;
}
endforeach;
print_r($acfField);
get_template_part( 'template-parts/post/content' );
endwhile;
注意:实际上,我们无法获取所有的 acf 字段。我们只能使用 post ID 获取特定帖子的所有 ACF 字段get_fields(get_the_ID());
于 2018-09-11T14:28:20.483 回答
0
您需要做的就是将此行添加到 function.php
<?php
function list_searcheable_acf(){
$list_searcheable_acf = array("title", "sub_title", "excerpt_short", "excerpt_long", "xyz", "myACF");
return $list_searcheable_acf;
}
function advanced_custom_search( $where, &$wp_query ) {
global $wpdb;
if ( empty( $where ))
return $where;
// get search expression
$terms = $wp_query->query_vars[ 's' ];
// explode search expression to get search terms
$exploded = explode( ' ', $terms );
if( $exploded === FALSE || count( $exploded ) == 0 )
$exploded = array( 0 => $terms );
// reset search in order to rebuilt it as we whish
$where = '';
// get searcheable_acf, a list of advanced custom fields you want to search content in
$list_searcheable_acf = list_searcheable_acf();
foreach( $exploded as $tag ) :
$where .= "
AND (
(wp_posts.post_title LIKE '%$tag%')
OR (wp_posts.post_content LIKE '%$tag%')
OR EXISTS (
SELECT * FROM wp_postmeta
WHERE post_id = wp_posts.ID
AND (";
foreach ($list_searcheable_acf as $searcheable_acf) :
if ($searcheable_acf == $list_searcheable_acf[0]):
$where .= " (meta_key LIKE '%" . $searcheable_acf . "%' AND meta_value LIKE '%$tag%') ";
else :
$where .= " OR (meta_key LIKE '%" . $searcheable_acf . "%' AND meta_value LIKE '%$tag%') ";
endif;
endforeach;
$where .= ")
)
OR EXISTS (
SELECT * FROM wp_comments
WHERE comment_post_ID = wp_posts.ID
AND comment_content LIKE '%$tag%'
)
OR EXISTS (
SELECT * FROM wp_terms
INNER JOIN wp_term_taxonomy
ON wp_term_taxonomy.term_id = wp_terms.term_id
INNER JOIN wp_term_relationships
ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
WHERE (
taxonomy = 'post_tag'
OR taxonomy = 'category'
OR taxonomy = 'myCustomTax'
)
AND object_id = wp_posts.ID
AND wp_terms.name LIKE '%$tag%'
)
)";
endforeach;
return $where;
}
add_filter( 'posts_search', 'advanced_custom_search', 500, 2 );
于 2018-09-11T14:34:58.003 回答