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:

    $ids = my_related_articles();
    $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>
<?php endwhile; endif; wp_reset_postdata(); ?> 

How I can fix this?

  • You have a typo. my_related_articles() and my_related_artickes(). Lets start there :) – Fredrik Jul 27 '20 at 13:42
  • fixed, but the problem still persist. – wpnewbie Jul 27 '20 at 13:46
  • The code who call the function is inside a template part, but I don't think is this the problem. single-related-loop.php is a proper name for the file and don't collide with wordpress. – wpnewbie Jul 27 '20 at 13:48
  • Du you get the correct categories from the var_dump? – Fredrik Jul 27 '20 at 13:48
  • nope. It output nothing. the function isn't fired I think! – wpnewbie Jul 27 '20 at 13:50

One 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.

  • This make sense. – Fredrik Jul 27 '20 at 14:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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