发布元标题未找到

时间:2016-05-10 20:47:37

标签: php wordpress search custom-post-type post-meta

我正在尝试构建并增强默认的wordpress搜索,以便您也可以搜索页面和自定义帖子类型元数据。它工作得很好,除了没有输出自定义字段标题。我做print_r($custom_fields);并显示存储的值。我只是迷失在我所缺少的东西上,但我认为它与跳过第一个值的两个foreach循环有关?

以下是显示正在发生的事情和代码的图片:

正在搜索的文字 Text being searched

搜索结果:查看Parkmerced(第一段): enter image description here

搜索结果:我们聚集在一起(第二段): enter image description here

functions.php (与搜索相关的功能)

function cf_search_join( $join ) {
    global $wpdb;

    if ( is_search() ) {
        $join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
    }

    return $join;
}
add_filter('posts_join', 'cf_search_join' );

function cf_search_where( $where ) {
    global $pagenow, $wpdb;

    if ( is_search() ) {
        $where = preg_replace(
            "/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
            "(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
    }

    return $where;
}
add_filter( 'posts_where', 'cf_search_where' );

function cf_search_distinct( $where ) {
    global $wpdb;

    if ( is_search() ) {
        return "DISTINCT";
    }

    return $where;
}
add_filter( 'posts_distinct', 'cf_search_distinct' );

的search.php     

<?php if ( have_posts() ) : ?>
<section class="search-results">
  <p class='show-results'><?php printf( __( 'Showing search results for: <span>%s', 'parkmerced-vision' ), get_search_query() ); ?></span></p>

  <?php while ( have_posts() ) : the_post(); ?>
    <!-- something found  -->


      <div class="result animated fade-in-up delay-<?php echo $i; ?>">
        <a href="<?php the_permalink(); ?>"><h4><?php the_title(); ?></h4></a>
        <?php
          the_excerpt();

          $searched =  get_search_query();
          $custom_fields = get_post_custom();

          foreach($custom_fields as $field_key => $field_values) {
            foreach($field_values as $key => $value) {

              if(stripos($value, $searched)) {

                $in = $value;
                $search = $searched;
                $replace = '<strong>' . $searched . '</strong>';

                $out = str_ireplace($search, $replace, $in);

                echo '<p>' . $out . '</p>';
              }
            }
          }
        ?>
      </div>

  <?php endwhile; else : ?>
    <!-- nothing found  -->

      <h2>Nothing Found</h2>
      <div class="alert alert-info">
        <p>Sorry, but nothing matched your search criteria. Please try again with some different keywords.</p>
      </div>
      <a class="search-back btn" href="<?php echo home_url('/'); ?>/faq">return to faq</a>

<?php endif; ?>

</section>


<?php get_footer(); ?>

1 个答案:

答案 0 :(得分:0)

问题不在于发布数据,而在于输出值本身。数组连接在一起,导致所有字符串的第一个单词附加到前面的数组值:

role?