"> 如何从帖-6ren">
gpt4 book ai didi

php - 如何从帖子页面的内容中显示实际的 "search term"并在 wordpress 中显示?

转载 作者:搜寻专家 更新时间:2023-10-31 21:25:06 25 4
gpt4 key购买 nike

我想在搜索结果页面上显示搜索词实际位于帖子内容中的句子或几个词,并显示它并在搜索词下划线。

对于标题我做了类似这样的:

<?php $title = get_the_title(); $keys= explode(" ",$s); $title = preg_replace('/('.implode('|', $keys) .')/iu', '<u class="search-excerpt">\0</u>', $title); ?>
<h3 class="test"><a href="<?php the_permalink(); ?>"><?php echo $title; ?></a></h3>

如何从帖子内容页面的实际“搜索词”中显示大约 15 个单词并显示它?

例如我想做类似的:

搜索词 = omnis

显示这个 = Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque

非常感谢,

最佳答案

在这里找到了一个答案: http://atastypixel.com/blog/keeping-blog-visitors-by-showing-meaningful-search-results-in-wordpress/

<?php
// Configuration
$max_length = 400; // Max length in characters
$min_padding = 30; // Min length in characters of the context to place around found search terms

// Load content as plain text
global $wp_query, $post;
$content = (!post_password_required($post) ? strip_tags(preg_replace(array("/\r?\n/", '@<\s*(p|br\s*/?)\s*>@'), array(' ', "\n"), apply_filters('the_content', $post->post_content))) : '');

// Search content for terms
$terms = $wp_query->query_vars['search_terms'];
if ( preg_match_all('/'.str_replace('/', '\/', join('|', $terms)).'/i', $content, $matches, PREG_OFFSET_CAPTURE) ) {
$padding = max($min_padding, $max_length / (2*count($matches[0])));

// Construct extract containing context for each term
$output = '';
$last_offset = 0;
foreach ( $matches[0] as $match ) {
list($string, $offset) = $match;
$start = $offset-$padding;
$end = $offset+strlen($string)+$padding;
// Preserve whole words
while ( $start > 1 && preg_match('/[A-Za-z0-9\'"-]/', $content{$start-1}) ) $start--;
while ( $end < strlen($content)-1 && preg_match('/[A-Za-z0-9\'"-]/', $content{$end}) ) $end++;
$start = max($start, $last_offset);
$context = substr($content, $start, $end-$start);
if ( $start > $last_offset ) $context = '...'.$context;
$output .= $context;
$last_offset = $end;
}

if ( $last_offset != strlen($content)-1 ) $output .= '...';
} else {
$output = $content;
}

if ( strlen($output) > $max_length ) {
$end = $max_length-3;
while ( $end > 1 && preg_match('/[A-Za-z0-9\'"-]/', $output{$end-1}) ) $end--;
$output = substr($output, 0, $end) . '...';
}

// Highlight matches
$context = nl2br(preg_replace('/'.str_replace('/', '\/', join('|', $terms)).'/i', '<strong>$0</strong>', $output));
?>

<p class="search_result_context">
<?php echo $context ?>
</p>

关于php - 如何从帖子页面的内容中显示实际的 "search term"并在 wordpress 中显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37895432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com