کد نمایش پست های مشابه در وردپرس

حسن غویشه

کاربر عضو
سلام 

شب بخیر

#سوال

یک افزونه نوشتم برای نمایش لیستی از پست های مرتبط زیر پست اصلی ولی کار نمیکنه (افزونه نصب و فعاله)

ظاهرا تابع های استفاده شده قدیمی هستند (وردپرس 3)

<?php

/*
Plugin Name: First Plugin
Plugin URI: https://candycode.ir/first-plugin
Description: my First WORDPRESS Plugin
Version: 1.0
Author: Micro
Author URI: https://candycode.ir
License: GPL2
*/



add_filter('the_content', function($content) {
$id = get_the_ID();
if (!is_singular('post'))
return $content;

$terms = get_the_terms($id, 'category');
$cats = [];

foreach ($terms as $term) {
$cats[] = $term->cat_ID;
}

$posts = new WP_Query([
'posts_per_page' => 2,
'category__in' => $cats,
'post__not_in' => [$id],
'orderby' => 'rand'
]);

if ($posts->have_posts()) {
$content .= '
<h2>پست های مرتبط</h2>
<ul class="related-posts">';

while ($posts->have_posts()) {
$posts->the_post();


$content .= '
<li>
<a href="'. get_permalink() . '"> '. get_the_title() .'</a>
</li>
';
}
$content .= '</ul>';

wp_reset_postdata();
}

return $content;

});




لطفا راهنمایی نمایید

سپاس :)

 

پیام یزدانیان

کاربر عضو
کد:
<?php

/*
Plugin Name: First Plugin
Plugin URI: https://candycode.ir/first-plugin
Description: my First WORDPRESS Plugin
Version: 1.0
Author: Micro
Author URI: https://candycode.ir
License: GPL2
*/


add_filter('the_content', 'related_posts_with_thumb', 2);
function related_posts_with_thumb($content){
global $post;
if( is_single() ){
$rel_posts = '';


$categories = get_the_category();
foreach($categories as $category){
	$rel_cat[] = $category->cat_ID;
}

$rep_args = array(
	'post__not_in' => array($post->ID), 
	'category__in' => $rel_cat, 
	'posts_per_page' => 5, 
	'orderby' => 'rand' 
);

$rep_query = new wp_query($rep_args);


if($rep_query->have_posts()){
while($rep_query->have_posts()) : $rep_query->the_post();
	$rel_img = get_the_post_thumbnail($post->ID, 'thumbnail'); 
	$rel_title =  get_the_title(); 
	$rel_link = get_permalink(); 
	$rel_posts .= "<div id='content_related_posts'> <a href='$rel_link'>$rel_img</a> <p><a href='$rel_link'> $rel_title </a></p></div>";
endwhile;
wp_reset_postdata();
}

$content .= "<h2 class='related_posts'>مطالب مرتبط</h2> $rel_posts";
}
return $content;
}
 
بالا