繁体   English   中英

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

[英]How can I show the actual “search term” from the content in the post page and display it in 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>

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

例如,我想做类似的:

搜索词= omnis

显示这个= Sed ut perspiciatis unde omn​​is 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>

如果您想使用插件,Relevanssi允许您为返回的结果使用自定义片段,您可以为搜索词设置长度和突出显示选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM