超短版:
更换
$post->post_title
具有
get_permalink($post->ID)
.
简短版本:
在当前代码中添加一个过滤器,您可以在其中输出
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>\';
在你的
functions.php
或插件文件:
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);
但为什么要停在这里?让我们改进提供的代码,并将其放到WordPress透视图中。
更好的方法WordPress有自己的帮助函数来返回选择的页面,例如页面。因此,与其只编写代码,不如尝试根据我们的需要复制和重写此函数。我称之为: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;
}
然后我们应用
list_pages
滤器
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);
最后我们可以
my_dropdown_post_type
功能类似于任何其他基本WP功能:
my_dropdown_post_type(
\'lesson\',
array(
\'selected\' => $my_dropdown,
\'post_status\'=> \'publish\',
\'suppress_filters\' => false,
\'posts_per_page\'=>-1
)
);