Super short version:
Replace $post->post_title
with get_permalink($post->ID)
.
Short version:
Add a filter to your current Code, where you output the post_title
.
$posts = get_posts(array('post_type'=> 'lesson', 'post_status'=> 'publish', 'suppress_filters' => false, 'posts_per_page'=>-1));
//here you add the HTML of the dropdown you add something like
echo '<p>Select the lesson: <select name="_dappcf_i_dropdown" class="widefat" style="width:170px" >';
foreach ($posts as $post) {
echo '<option value="', $post->ID, '"';
if ($my_dropdown == $post->ID){echo ' selected="selected"';}
echo '>'.
apply_filters('filter_list_cpt', $post->post_title, $post).
'</option>';
}
echo '</select>';
Somewhere in your functions.php
or plugin file:
function filter_list_cpt($title, $cpt) {
return sprintf(__('%1$s [%2$s]', 'my_textdomain'), $title, get_permalink($cpt->ID));
}
add_filter('list_cpt', 'filter_list_cpt', 10, 2);
But why stop here? Let us improve the provided code and put it into a WordPress perspective.
Better approach
WordPress has its own helper functions to return a select of e.g. pages. So instead of just writing code, lets try to copy and rewrite this function to our needs. I call it: my_dropdown_post_type
function my_dropdown_post_type( $post_type="lesson", $args="" ) {
$defaults = array(
'depth' => 0, 'child_of' => 0,
'selected' => 0, 'echo' => 1,
'name' => "{$post_type}_id", 'id' => '',
'class' => '',
'show_option_none' => '', 'show_option_no_change' => '',
'option_none_value' => '',
'value_field' => 'ID',
'post_type' => $post_type
);
$r = wp_parse_args( $args, $defaults );
$cpt = get_posts( $r );
$output="";
if ( ! empty( $cpt ) ) {
$class="";
if ( ! empty( $r['class'] ) ) {
$class = " class="" . esc_attr( $r["class'] ) . "'";
}
$output = "<select name="" . esc_attr( $r["name'] ) . "'" . $class . " id='" . esc_attr( $r['id'] ) . "'>\n";
if ( $r['show_option_no_change'] ) {
$output .= "\t<option value=\"-1\">" . $r['show_option_no_change'] . "</option>\n";
}
if ( $r['show_option_none'] ) {
$output .= "\t<option value=\"" . esc_attr( $r['option_none_value'] ) . '">' . $r['show_option_none'] . "</option>\n";
}
$output .= walk_page_dropdown_tree( $cpt, $r['depth'], $r );
$output .= "</select>\n";
}
$html = apply_filters( 'wp_dropdown_pages', $output, $r, $cpt );
if ( $r['echo'] ) {
echo $html;
}
return $html;
}
Then we apply our list_pages
filter
function filter_list_cpt($title, $cpt) {
if ($cpt->post_type == 'lesson')
return sprintf(__('%1$s [%2$s]', 'my_textdomain'), $title, get_permalink($cpt->ID));
return $title;
}
add_filter('list_pages', 'filter_list_cpt', 10, 2);
In the end we can call our my_dropdown_post_type
function like any other basic WP function:
my_dropdown_post_type(
'lesson',
array(
'selected' => $my_dropdown,
'post_status'=> 'publish',
'suppress_filters' => false,
'posts_per_page'=>-1
)
);