自定义分类法中通过 ACF 字段的 Wordpress 搜索表单和搜索结果

Wordpress search form and search result through ACF field in custom taxonomy

所以我觉得我是在为自己过日子。

我的网站上有一个搜索字段,我已将其分成 3 个,例如:

<input type="text" name="part1" />
<input type="text" name="part2" />
<input type="text" name="part3" />

在我的结果页面上,我创建了搜索字符串,例如:

$searchstring = $part1.'-'.$part2.'-'.$part3;

接下来的过程是在数据库中搜索值为 $searchstring

的自定义字段

我在那里找到了一个搜索功能 https://gist.github.com/jserrao/d8b20a6c5c421b9d2a51,我认为它非常接近我想要实现的目标,但我不确定如何实现其中的所有功能。

我的数据大致是这样的:

(taxonomy) product_cat - (name) Category 1 - (custom field) gc_number - (value I need to search) 77-999-77
(taxonomy) product_cat - (name) Category 2 - (custom field) gc_number - (value I need to search) 73-333-73
(taxonomy) product_cat - (name) Category 3 - (custom field) gc_number - (value I need to search) 76-666-76

然后我需要向用户显示 product_cat 名称。

希望这是有道理的,我们将不胜感激!

来自 ACF 文档

$posts = get_posts(array(
    'numberposts'   => -1,
    'post_type'     => 'post',
    'meta_key'      => 'color',
    'meta_value'    => 'red'
));

此示例显示用于查找名为“color”的自定义字段值为“red”的所有帖子的参数。在您的情况下,您应该对 meta_key 使用 gc_number,对 meta_value 使用 $searchstring。然后你可以使用 get_the_terms() 来定义帖子属于哪个类别术语。

我在 Stack Exchange - Wordpress Development 上问了这个问题,并从 Kieran McClung 那里得到了很好的回答。他的回答非常适合我,复制如下。

<form role="search" method="get" id="acf-search" action="<?php site_url(); ?>">
...

<input type="text" name="part1" />
<input type="text" name="part2" />
<input type="text" name="part3" />

<input type="submit" value="Search" />
</form>


<?php
// Results page

// Might be worth checking to make sure these exist before doing the query.
$part_1 = $_GET['part1'];
$part_2 = $_GET['part2'];
$part_3 = $_GET['part3'];
$search_string = $part_1 . '-' . $part_2 . '-' . $part_3;

// Get all product categories
$categories = get_terms( 'product_cat' );
$counter = 0;

// Loop through categories
foreach ( $categories as $category ) {

    // Get custom field
    $gc_number = get_field( 'gc_number', $category );

    // If field matches search string, echo name
    if ( $gc_number == $search_string ) {
        // Update counter for use later
        $counter++;
        echo $category->name;
    }
}

// $counter only increases if custom field matches $search_string.
// If still 0 at this point, no matches were found.
if ( $counter == 0 ) {
    echo 'Sorry, no results found';
}
?>