如何显示帖子页面内容中的实际“搜索词”并将其显示在 WordPress 中?

Hop*_*one 5 php wordpress

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

对于标题我做了类似的事情:

<?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>
Run Code Online (Sandbox Code Playgroud)

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

例如我想做类似的:

搜索词 = 全方位

显示此 = Sed ut perspiciatis undeomnis iste natus error sat voluptatem Accusantium doloremque

非常感谢,

Hop*_*one 3

在这里找到了一个答案: 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>
Run Code Online (Sandbox Code Playgroud)