Support » Plugins » Hacks » Getting Post ID, Name and Category for use in Plugin

  • I want to create a HTML select tag populated with the Post Title and with the value of the post ID for use in a small Plugin I am working on.
    I only want Posts that are assigned to a certain category, i.e. latest-news.
    I am confused with the database structure WP uses and cannot formulate a SQL query to retrieve the result set I want.
    I am also using the $wpdb->get_results syntax.
    Can anybody create the SQL query that will return the Post Title, Post ID and Post Category?
    I am using WP 3.4.2.
    Thanks in advance people.

Viewing 1 replies (of 1 total)
  • You don’t have to build your own SQL query. Instead you might either use the function get_posts($args) (

    $posts = get_posts( array(
        'post_type'   => 'post',
        'post_status' => 'publish',
        'category'    => 'myCategory'

    or build your own custom loop (

    $Custom = new WP_Query(
        'post_type'     => 'post',
        'category__in'  => array( 'myCategory' ),
        'post_status'   =>'publish'

    WP_Query is a more powerful in terms of configuration but if you only need the datasets you listed get_posts might be good, too.

    $html = '<select>';
    // In case of the custom loop use $Custom->posts instead of $posts to loop through)
    foreach( $posts as $item ) {
      $html .= ' <option value="' . $item->ID . '">' . $item->post_title . '</option>';
    $html .= '</select>';
Viewing 1 replies (of 1 total)
  • The topic ‘Getting Post ID, Name and Category for use in Plugin’ is closed to new replies.