How to use custom function in posts and pages templates

Question

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?

0
wpnewbie 1 year 2020-07-27T09:11:16-05:00 0 Answers 42 views 0

Leave an answer

Browse
Browse