如何在我的Algolia搜索页面结果的摘录中显示我的Wordpress自定义字段属性

How do I display my Wordpress custom field attribute in the excerpt of my Algolia Search page results?

本文关键字:我的 显示 Wordpress 自定义 属性 字段 结果 Algolia 搜索      更新时间:2023-09-26

我目前在Worpdress内使用Algolia的搜索插件。我已经成功地将一些自定义字段及其值推送到Algolia中的自定义属性。现在,我试图在我的搜索结果中包含一个名为"program_description"的自定义属性。

默认情况下,搜索只返回'post_title'和'content'属性的值。我有兴趣用我的自定义属性的输出('program_description')替换'content'属性输出。

我想我会简单地修改instantsearch.php模板,将'program_description'添加到属性数组中,如下所示:

<div class="ais-hits--content">
    <h3 itemprop="name headline"><a href="{{ data.permalink }}" title="{{ data.post_title }}" itemprop="url">{{{ data._highlightResult.post_title.value }}}</a></h3>
    <div class="ais-hits--tags">
        <# for (var index in data.taxonomies.post_tag) { #>
        <span class="ais-hits--tag">{{{ data._highlightResult.taxonomies.post_tag[index].value }}}</span>
        <# } #>
    </div>
    <div class="excerpt">
        <p>
            <#
            var attributes = ['program_description', 'content', 'title6', 'title5', 'title4', 'title3', 'title2', 'title1'];
            var attribute_name;
            var relevant_content = '';
            for ( var index in attributes ) {
                attribute_name = attributes[ index ];
                if ( data._highlightResult[ attribute_name ].matchedWords.length > 0 ) {
                    relevant_content = data._snippetResult[ attribute_name ].value;
                }
            }
            relevant_content = data._snippetResult[ attributes[ 0 ] ].value;
            #>
            {{{ relevant_content }}}
        </p>
    </div>
</div>

这样做,我的结果没有返回,我遇到以下控制台错误:Uncaught TypeError: Cannot read property 'matchedWords' of undefined

Cannot read property 'matchedWords' of undefined告诉我您的attributes的自定义参数可能没有在Algolia范围内定义。

我建议用您的自定义属性(或您将使用的任何属性)初始化attributesToIndex -这样您就可以确保attributesToHighlight具有可以使用的定义。

查看这个答案~它可能有助于阐明为什么您在尝试访问_highlightResult对象的matchedWords成员时为自定义属性获得undefined定义