Sorting posts on a WordPress site with custom SQL

I have a php function that generates a comma separated list of Post IDs that specify the order those posts should display on my WordPress site.

I’m looking for a place I can insert an SQL query like:

Read More
SELECT * FROM wp_posts WHERE ID IN ('1', '2', '3')

Which .php file should I modify? How should I phrase the SQL?

Related posts

Leave a Reply

3 comments

  1. Paste your php function in file (root wordpress folder)/wp-content/themes/(name of your theme)/functions.php
    SQL query should be like.

    $sql=$wpdb->prepare("SELECT * FROM wp_posts WHERE ID IN ('1', '2', '3');");
    $results=$wpdb->get_results($sql);          
    echo ">>>>".$result[0]->something."<br />";//blah blah...
    

    WoW,i did not mention $wpdp as global,still code was working fine on my system!,anyways
    i would suggest you write “global $wpdb” in your function.

    Now the main question is from where should you call this function;
    you have to call it from theme/(your theme)/index.php

    Try figuring out how the posts are generated in your current theme,and you might get what you need to do!

  2. First off you should use wp_query for this. It is designed to query posts.

    <?php
    $args = array(
        'post__in' => array ( 1,2,3) //the Ids
    );
    $query = new WP_Query($args);
    if ($query->have_posts()){
        while ($query->have_posts()) {
            $query->the_post();
            echo get_the_ID().'<br/>';
        }
    
    } else {
        echo 'no posts found';
    }
    

    About the placement
    I advise to do it in a custom template, make a simple template with the code above, create a page assign it that template and make the page private.

  3. global $wpdb; $results = $wpdb->get_results("SELECT * FROM {$wpdb->posts} WHERE ID IN (1, 2, 3) ORDER BY ID");
    

    You can use that in your theme’s functions.php file.