如何检索特定帖子类型的所有帖子标题?

时间:2016-09-21 作者:Peter Turner

我想在我回复给客户端的表单中使用select元素中的标题。最好的方法是什么?

4 个回复
最合适的回答,由SO网友:Ahmed Fouad 整理而成

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();
SO网友:Nicolai Grossherr

在我看来,您可以使用API函数来获取数据。

// query for your post type
$post_type_query  = new WP_Query(  
    array (  
        \'post_type\'      => \'your-post-type\',  
        \'posts_per_page\' => -1  
    )  
);   
// we need the array of posts
$posts_array      = $post_type_query->posts;   
// create a list with needed information
// the key equals the ID, the value is the post_title
$post_title_array = wp_list_pluck( $posts_array, \'post_title\', \'ID\' );

SO网友:birgire

对于hierarchical post类型,我们有内置的:

wp_dropdown_pages( 
    [ 
        \'post_type\' => \'page\',
        \'echo\'      => 1, 
        \'name\'      => \'wpse_titles\', 
        \'id\'        => \'wpse-titles\' 
    ] 
);
这将生成一个select元素,并将post titles和post ID作为选项值。

Example:

<select name=\'wpse_titles\' id=\'wpse-titles\'>
    <option class="level-0" value="1">AAA</option>
    <option class="level-0" value="2">BBB</option>
    <option class="level-1" value="3">&nbsp;&nbsp;&nbsp;CCC</option>
</select>
现在还不清楚documentation 对于wp_dropdown_pages(), 但这是一个包装get_pages() 还支持它的输入参数。

SO网友:Tim Roberts

我一直这样做的方式是get_postsforeach 如下所示:

// Create our arguments for getting our post
$args = [
  \'post_type\'=>\'custom-slug\'
];

// we get an array of posts objects
$posts = get_posts($args);

// start our string
$str = \'<select>\';
// then we create an option for each post
foreach($posts as $key=>$post){
  $str .= \'<option>\'.$post->post_title.\'</option>\';
}
$str .= \'</select>\';
echo $str;