Title: SQL Statement for getting custom postfield
Last modified: August 22, 2016

---

# SQL Statement for getting custom postfield

 *  [joh3](https://wordpress.org/support/users/joh3/)
 * (@joh3)
 * [11 years, 7 months ago](https://wordpress.org/support/topic/sql-statement-for-getting-custom-postfield/)
 * Hello,
    I created a post_ranking field in the wp_posts table. Now I want to get
   the posts sorted by their post_ranking. I don’t get any Post back with my statement:
 *     ```
       add_filter('posts_orderby', 'ranking_order');
       function ranking_order($orderby)
       {global $wpdb;
       $orderby = "SELECT distinct $wpdb->posts.* from $wpdb->posts where $wpdb->posts.post_type = 'listing' order by $wpdb->posts.post_ranking DESC";
       return $orderby;}
       ```
   
 * I’m glad for any help!

Viewing 1 replies (of 1 total)

 *  Moderator [bcworkz](https://wordpress.org/support/users/bcworkz/)
 * (@bcworkz)
 * [11 years, 7 months ago](https://wordpress.org/support/topic/sql-statement-for-getting-custom-postfield/#post-5404932)
 * You should only be returning the order by clause with this filter. What you are
   doing is causing a SQL syntax error.
 * If you want to replace the entire query string, use ‘posts_request’ filter.
 * You should know that modifying default WP table structures is a bad idea. It 
   could prevent Wp from properly updating the structure in a future WP update, 
   causing the entire WP update to fail.
 * You should either use post meta or join in a custom table by post ID to add additional
   data to posts.

Viewing 1 replies (of 1 total)

The topic ‘SQL Statement for getting custom postfield’ is closed to new replies.

 * In: [Hacks](https://wordpress.org/support/forum/plugins-and-hacks/hacks/)
 * 1 reply
 * 2 participants
 * Last reply from: [bcworkz](https://wordpress.org/support/users/bcworkz/)
 * Last activity: [11 years, 7 months ago](https://wordpress.org/support/topic/sql-statement-for-getting-custom-postfield/#post-5404932)
 * Status: not resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
