Me gustaría usar los títulos dentro de un elemento de selección en una forma que estoy haciendo eco al lado del cliente. ¿Cuál sería la mejor manera de hacer esto?
Me gustaría usar los títulos dentro de un elemento de selección en una forma que estoy haciendo eco al lado del cliente. ¿Cuál sería la mejor manera de hacer esto?
Consultar todos los títulos de publicaciones de un tipo de publicación específico
// 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();
Podrías, y en mi opinión, deberías usar las funciones de API para obtener los datos.
// 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' );
Para un tipo de publicación jerárquica , tenemos el incorporado:
wp_dropdown_pages(
[
'post_type' => 'page',
'echo' => 1,
'name' => 'wpse_titles',
'id' => 'wpse-titles'
]
);
que generará un elemento select con post títulos y post ID como valor de opción.
Ejemplo :
<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"> CCC</option>
</select>
No está claro en la documentación de para wp_dropdown_pages()
, pero es un contenedor para get_pages()
y También apoya sus argumentos de entrada.
La forma en que siempre he hecho cosas como esta es usar get_posts
y foreach
como algo a continuación:
// 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;
Lea otras preguntas en las etiquetas wp-query custom-post-types