where to put database query in wordpress file?

I am trying to put the following query in wordpress site, where do i put this query ? should i create plugin for general database queries or there are other ways. I am trying to get results of various query in my template.

$pop = $wpdb->get_results("SELECT id, post_title,FROM posts WHERE post_type='post' ORDER BY comment_count DESC LIMIT 10");  
 foreach($pop as $post) : ?>  
 <li> <?php echo $post->post_title; ?> </li>  
 <?php endforeach; ?> 

Related posts

Leave a Reply

1 comment

  1. You can put this query in your themes functions.php file :

    $pop = $wpdb->get_results("SELECT id, post_title,FROM posts WHERE post_type='post' ORDER BY comment_count DESC LIMIT 10");  
    foreach($pop as $post) : ?>  
         <li> <?php echo $post->post_title; ?> </li>  
    <?php endforeach; ?> 
    

    If you put the query in any WordPress core files, when you update WordPress to the latest version your changes will be lost.

    Hope this helps 🙂