【发布时间】:2020-10-05 18:57:35
【问题描述】:
首先,我在 WordPress 中使用 Timber (TWIG)。这就是为什么只使用 PHP 会有一些不同的原因。
我用搜索词高亮系统(带有“mark”js插件)实现了WordPress搜索功能。
一切正常,但是我想将包含搜索词的段落显示为摘录。
例如,如果我使用“扬声器”一词进行搜索。我想在结果中显示包含单词“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),
'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
));
}
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 %}
【问题讨论】: