问题描述
首先,我在wordpress中使用Timber(TWIG)。这就是为什么仅使用PHP会有一些差异。
我通过搜索的单词突出显示系统(带有“ mark” js插件)实现了wordpress搜索功能。
例如,如果我在搜索中使用单词“ speaker”。我想在结果中显示包含单词“ speaker”的段落。
要插入适当的段落而不是card.article_exceprt
(
参见下面的完整代码):
<div class="card__content">
{{ card.article_exceprt }}
</div>
该怎么做?
script.js
function init_datas_fetch() {
$('#search-form').on('submit',function(e) {
e.preventDefault();
var searchValue = $('#search-input').val();
if (searchValue.length > 0) {
$.ajax({
type: 'POST',url: '/wp-admin/admin-ajax.PHP',dataType: 'html',data: {
'action' : 'datas_fetch','terms' : searchValue
},success: function(data) {
$('#fetch-list').html(data);
},error: function(data) {
}
});
} else {
$('#fetch-list').html('');
}
});
}
functions.PHP
add_action( 'wp_ajax_nopriv_datas_fetch','datas_fetch' );
add_action( 'wp_ajax_datas_fetch','datas_fetch' );
function datas_fetch() {
$context['page_search'] = true;
$keywords = isset($_POST['terms']) ? $_POST['terms'] : '';
$posts_types_selected = array('pages' => 'page','articles' => 'post','videos' => 'videos','podcasts' => 'podcasts');
$exclude_posts = get_field('search_exclude','option');
$Meta_query = array(
'relation' => 'OR'
);
if (!empty($keywords)) {
$fields = array(
'article_exceprt','article_chapeau','blocs_article_$_article_wysiwyg'
);
foreach($fields as $field) {
array_push($Meta_query,array(
'key' => $field,'value' => $keywords,'compare' => 'LIKE'
));
}
}
if ($keywords) {
$context['posts'] = Timber::get_posts(array(
'post_type' => array_values($posts_types_selected),'post_status' => 'publish','posts_per_page' => -1,'paged' => 1,'orderby' => 'date','order' => 'DESC','post__not_in' => array_values($exclude_posts),'hide_empty' => true,'has_password' => FALSE,'_Meta_or_title' => $keywords,'Meta_query' => $Meta_query
));
} else {
$context['posts'] = Timber::get_posts(array(
'post_type' => array_values($posts_types_selected),'has_password' => FALSE
));
}
Timber::render( 'bloc_fetch.twig',$context );
die();
}
tpl_search.twig
<form role="search" id="search-form">
<input type="text" id="search-input" class="search__input" placeholder="{{ __('Rechercher des articles,vidéos...','cmd') }}" value="">
<input type="submit" id="search-submit" class="search__button" value="Rechercher">
</form>
<div id="fetch-list">
{% include "bloc_fetch.twig" %}
</div>
bloc_fetch.twig
{% for card in posts %}
<div class="card">
<img src="{{ card.thumbnail.src }}" class="card__visual" alt="{{ card.thumbnail.alt }}">
<a href="{{ card.link }}" class="card__link"></a>
<div class="card__content">
{{ card.article_exceprt }}
</div>
</div>
{% endfor %}
解决方法
如果您尝试检索自定义字段,请使用:
{{ card.meta('article_exceprt') }}
否则对于 post excert,请尝试:
{{ card.preview }}