I want to add a custom function to get related posts into my wp theme.
I have added this function code to my theme functions.php file but it will not work:
function my_related_artickes()
{
$categories = wp_get_post_categories( $post->ID );
$ids = array();
foreach( $categories as $cat ){
$ids[] = $cat;
}
return $ids;
}
I'm calling the function in this way:
<?php
$ids = my_related_articles();
var_dump($ids);
$related = new WP_Query( array('post_type' => 'post', 'category__in' => $ids, 'posts_per_page' => 4 ) );
if( $related->have_posts() ): while( $related->have_posts() ): $related->the_post();
?>
<div class="col-md-3 col-lg-3 mt-3 mb-3 d-none d-md-block">
<img class="img-fluid w-100 related-img mb-3" src="<?php echo the_post_thumbnail_url(); ?>">
<a class="h5 text-decoration-none" href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</div>
<?php endwhile; endif; wp_reset_postdata(); ?>
How I can fix this?
I want to add a custom function to get related posts into my wp theme.
I have added this function code to my theme functions.php file but it will not work:
function my_related_artickes()
{
$categories = wp_get_post_categories( $post->ID );
$ids = array();
foreach( $categories as $cat ){
$ids[] = $cat;
}
return $ids;
}
I'm calling the function in this way:
<?php
$ids = my_related_articles();
var_dump($ids);
$related = new WP_Query( array('post_type' => 'post', 'category__in' => $ids, 'posts_per_page' => 4 ) );
if( $related->have_posts() ): while( $related->have_posts() ): $related->the_post();
?>
<div class="col-md-3 col-lg-3 mt-3 mb-3 d-none d-md-block">
<img class="img-fluid w-100 related-img mb-3" src="<?php echo the_post_thumbnail_url(); ?>">
<a class="h5 text-decoration-none" href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</div>
<?php endwhile; endif; wp_reset_postdata(); ?>
How I can fix this?
Share Improve this question edited Jul 27, 2020 at 13:28 wpnewbie asked Jul 27, 2020 at 13:19 wpnewbiewpnewbie 135 bronze badges 9 | Show 4 more comments1 Answer
Reset to default 2One problem (there may be more ;-) is that $post->ID
is probably out of scope when you call it from the page template.
You could change the way the function works to take the post ID as a parameter, like this:
function my_related_artickes($postID)
{
$categories = wp_get_post_categories( $postID );
$ids = array();
foreach( $categories as $cat ){
$ids[] = $cat;
}
return $ids;
}
Then call it like this:
$ids = my_related_articles($post->ID);
Obviously when you call it make sure that you give it a good post ID.
single-related-loop.php
is a proper name for the file and don't collide with wordpress. – wpnewbie Commented Jul 27, 2020 at 13:48