Getting Post ID, Name and Category for use in Plugin (2 posts)

  1. mitel
    Posted 3 years ago #

    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.

  2. Chris
    Posted 3 years ago #

    You don't have to build your own SQL query. Instead you might either use the function get_posts($args) (http://codex.wordpress.org/Template_Tags/get_posts)

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

    or build your own custom loop (http://codex.wordpress.org/Class_Reference/WP_Query)

    $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>';

Topic Closed

This topic has been closed to new replies.

About this Topic