Attempting to pass a variable to a Wordpress function

Hi my fellow developers. I am trying to modify a secondary Wordpress query and display a list of messages according to the category of parent messages. It currently outputs html to create a message, however it does not match the category. What am I missing here? Thanks in advance.

<?php $the_category = get_the_category($post->ID); global $post; $myposts = get_posts('numberposts=5&category='.$the_category.''); foreach($myposts as $post) : setup_postdata($post); ?> <li> <div class="suggestVid"> <span style="padding-right:5px; float:left;"> <?php the_post_thumbnail('suggest-vid'); ?></span> <a href="<?php the_permalink() ?>"><?php the_title(); ?></a> </div> </li> <?php wp_reset_postdata(); ?> <?php endforeach; ?> <?php wp_reset_query(); ?> 
+5
source share
2 answers

You call get_the_category($post->ID); and think that it just returns a category when it actually returns an array of category objects . Assuming that each message has only one category, you can simply take the first result that was returned.

You also mixed the order wp_reset_postdata(); and endforeach; . You complete the reset of the mail data inside your loop so that it always returns to the current page after each iteration of the loop. You only want to reset after the loop finishes.

In addition, if you are inside The Loop , for example, on a template page, you do not need to specify global $post; directly.

Try the following:

 $categories = get_the_category(); $category = $categories[0]; $myposts = get_posts(array( 'posts_per_page' => 5, 'category' => $category->cat_ID )); ?><ul><?php foreach($myposts as $post) : setup_postdata($post); ?> <li> <div class="suggestVid"> <span style="padding-right:5px; float:left;"> <?php the_post_thumbnail('suggest-vid'); ?></span> <a href="<?php the_permalink() ?>"><?php the_title(); ?></a> </div> </li><?php endforeach; wp_reset_postdata(); 

? >

+3
source

Replace this:

 $myposts = get_posts('numberposts=5&category='.$the_category.''); 

from

 $myposts = get_posts('numberposts=5&category='.$the_category); 

Do not use $post as a keyword in programming, because $post is a reserved keyword for WordPress.

+2
source

Source: https://habr.com/ru/post/1209635/


All Articles