我有以下基于this great template的代码用于制作自定义WordPress小部件:
<?php class DRCC_Feat extends WP_Widget {
function dr_post_select_list() {
$drcc_posts_args = array(
'post_type' => array( 'post', 'page', 'tribe_events' ),
'numberposts' => -1,
'orderby' => 'title',
'order' => 'ASC'
);
$drcc_posts = get_posts( $drcc_posts_args );
$dr_posts_array = array();
foreach( $drcc_posts as $post ) {
$dr_posts_array[$post->ID] = $post->post_title;
}
return $dr_posts_array;
}
protected $widget = array(
'description' => 'Custom widget for my client.',
'do_wrapper' => true,
'view' => false,
'fields' => array(
array(
'name' => 'Post to Feature',
'desc' => 'Enter the IDs of any posts, pages, etc. If more than one, separate with commas.',
'id' => 'dr_feat_ids',
'type' => 'select',
'options' => dr_post_select_list(),
'std' => ''
)
)
);
// some more stuff here, but the error is above and the code works when I make 'options' somethings hard-coded.
} ?>
我正在尝试在受保护的dr_post_select_list()
数组中调用$widget
来动态生成帖子列表,但我在{{1}引用的行中收到错误Parse error: syntax error, unexpected '(', expecting ')'
功能在它。就好像它没有意识到它是一个功能。
我在其他地方尝试了这个功能,但它运行正常。我已经尝试将数组公开,并且不会改变任何内容。我已经尝试将函数输出保存在数组中并将变量放在数组中
我觉得我做的事情从根本上是错误的。
tl; dr - 类中数组中调用的方法不运行(或者似乎被识别为方法)。
答案 0 :(得分:2)
您错过了函数的结束}
。
使用以下内容替换您的代码:
<?php
class DRCC_Feat extends WP_Widget {
protected $widget = array(
'description' => 'Custom widget for my client.',
'do_wrapper' => true,
'view' => false,
'fields' => array(
array(
'name' => 'Post to Feature',
'desc' => 'Enter the IDs of any posts, pages, etc. If more than one, separate with commas.',
'id' => 'dr_feat_ids',
'type' => 'select',
'options' => 'dr_post_select_list',
'std' => ''
)
)
);
function dr_post_select_list() {
$drcc_posts_args = array(
'post_type' => array( 'post', 'page', 'tribe_events' ),
'numberposts' => -1,
'orderby' => 'title',
'order' => 'ASC'
);
$drcc_posts = get_posts( $drcc_posts_args );
$dr_posts_array = array();
foreach( $drcc_posts as $post ) {
$dr_posts_array[$post->ID] = $post->post_title;
}
return $dr_posts_array;
}
}
编辑:移动了类内的所有代码,纠正了错误。关于在数组中存储函数的问题,请看一下这篇文章。与JS说的略有不同。 Can you store a function in a PHP array?