0

我有以下代码基于这个用于制作自定义 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数组以动态生成帖子列表,但是Parse error: syntax error, unexpected '(', expecting ')'在引用其中包含dr_post_select_list()函数的行时出现错误。就好像它不承认它是一个函数。

我在别处试过这个功能,效果很好。我已经尝试将数组公开,但这并没有改变任何东西。我尝试将函数输出保存在数组中并将变量放入数组中

我感觉到我在做一些根本错误的事情。

tl; dr - 在类中的数组中调用的方法不运行(或似乎被识别为方法)。

4

1 回答 1

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略有不同。 您可以将函数存储在 PHP 数组中吗?

于 2012-07-06T01:39:27.680 回答