• Resolved greggor

    (@greggor)


    I’m running a theme that makes a call to the meta info of posts, finds a specific value and lists the posts in DSC order based on the value of that custom field.

    I use a naked MYSQL query in the sidebar.php file, but I have some security concerns.

    Here’s the code:

    <ul id="top-sites">
    				 <?php
    
     $querystr = "
        SELECT wposts.*
        FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
        WHERE wposts.ID = wpostmeta.post_id
        AND wpostmeta.meta_key = 'score'
        AND wposts.post_status = 'publish'
        AND wposts.post_type = 'post'
        ORDER BY wpostmeta.meta_value DESC
     ";
    
     $pageposts = $wpdb->get_results($querystr, OBJECT);
    
     ?>
    
    				  <?php if ($pageposts): ?>
     <?php foreach ($pageposts as $post): ?>
     <?php setup_postdata($post); ?>
    
    				<?php static $count1 = 0; if ($count1 == "10") { break; } else { ?>
    
    					<li><a href="<?php the_permalink();?>"><?php
    				echo get_post_meta($post->ID, 'sitename', true); ?></a> <span class="small">(<?php echo get_post_meta($post->ID, 'score', true); ?>)</span></li>
    				<?php $count1++; } ?>
    				<?php endforeach; ?>
    				 <?php else : ?><?php endif; ?>
    				</ul>

    I can’t figure out how to make the query a function and bury it in a safe place where the sql query won’t be exposed. It works as it is now. Can anyone point me in the right direction here?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Not too sure of what the security issue is, but you could resort to using a new WP_Query or get_posts to do what the SQL statement is doing.

    See the query_posts() for a list of the arguments.

    Thread Starter greggor

    (@greggor)

    Wow, I don’t remember the query_posts having had so much power last time i was in there! The issue was having that MYSql query on a template page – – where it would be possible that someone could see it, possibly.

    ANyway this is what works now, thank you for your help!

    <ul id="top-sites">
    				<?php query_posts('meta_key=score&orderby=meta_value'); ?>
    				<?php
    				while (have_posts()) : the_post(); ?>
    				<?php static $count1 = 0; if ($count1 == "10") { break; } else { ?>
    
    					<li><a href="<?php the_permalink();?>"><?php
    				echo get_post_meta($post->ID, 'sitename', true); ?></a> <span class="small">(<?php echo get_post_meta($post->ID, 'score', true); ?>)</span></li>
    				<?php $count1++; } ?>
    
    				 <?php endwhile; ?>
    				</ul>

    Works like a charm, and is so much easier… 😛

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Database Query, moving out of template but to where?’ is closed to new replies.