0

I have a related posts loop ( in every single post page ) based on post title. source : https://wpza.net/get-related-posts-based-on-the-posts-content-in-wordpress/

But I also need to include current post into this loop 'post__in' => $similar, . Please can anyone help me how can I do this

function custom_related_posts() {
     $current_id = get_the_ID();
      $current_content = get_the_title( $current_id );
     $similar = array();
     $scores = array();
     $percentage = 0;
     $output = '';

     function compare_content( $current_content, $comparison_content ) {
          $current_content = trim( strtolower( $current_content ) );
          $comparison_content = trim( strtolower( $comparison_content ) );
          similar_text( $current_content, $comparison_content, $percentage );
          $formated_percents = number_format( $percentage );
          return $formated_percents; 
     }

     $args = array(
          'post_type' => 'product',
          'posts_per_page' => -1
     );
     $loop = new wp_query( $args );
     while( $loop->have_posts() ) {
          $loop->the_post();
           $score = compare_content( $current_content, get_the_title() );
          if ( $score > 90 && get_the_ID() != $current_id ) {
               array_push( $similar, get_the_ID() );
               array_push( $scores, $score );
          }
     }
     wp_reset_query();

     array_multisort( $scores, SORT_NUMERIC, SORT_DESC, $similar );

     if ( ! empty( $similar ) ) {
          $args = array(
               'post_type' => 'product',
               'posts_per_page' => 100,
               'post__in' => $similar,
               'orderby' => 'meta_value_num',
'order' => 'asc',
'meta_key' => '_price'
          );
          $loop = new wp_query( $args );
          $i = -1;
          while ( $loop->have_posts() ) {
               $loop->the_post();
               $i++;
               echo do_shortcode('[wbcr_snippet id="22379"]') ; echo  '<div class="ai">'. $scores[$i] .'% oxsar mehsul</div>'; 
          }
          wp_reset_query();
     }
     return $output;
}
1
  • 1
    Side note, thank you for referencing our source — we appreciate it! :)
    – WPZA
    Apr 8, 2022 at 14:30

1 Answer 1

2

I'm not sure why you'd want a post you're already looking at to be in the similar... but off topic I guess.

You ask it not to include the $current_id in this line here

if ( $score > 90 && get_the_ID() != $current_id ) {
2
  • thank for your help. we are createing product price comparision website. Apr 8, 2022 at 10:44
  • Thank you it worked != $none Apr 8, 2022 at 10:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.