How to retrieve all post titles of a specific post type?

Query all post titles of a specific post type

// Function that returns post titles from specific post type as form select element
// returns null if found no results.

function output_projects_list() {
    global $wpdb;

    $custom_post_type="page"; // define your custom post type slug here

    // A sql query to return all post titles
    $results = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = %s and post_status="publish"", $custom_post_type ), ARRAY_A );

    // Return null if we found no results
    if ( ! $results )
        return;

    // HTML for our select printing post titles as loop
    $output="<select name="project" id="project">";

    foreach( $results as $index => $post ) {
        $output .= '<option value="' . $post['ID'] . '">' . $post['post_title'] . '</option>';
    }

    $output .= '</select>'; // end of select element

    // get the html
    return $output;
}

// Then in your project just call the function
// Where you want the select form to appear
echo output_projects_list();

Leave a Comment