在wordpress中使用回调键传递参数

时间:2016-02-12 13:45:26

标签: php wordpress

我在这里使用WordPress。我有以下代码:

if (is_product() && is_woocommerce() && $this->category_has_fiance() == true) { 
            $tabs['finance_tab'] = array(
                'title'     => __( 'Finance Options', 'woocommerce' ),
                'priority'  => 50,
                'callback'  => array ($this, 'woo_finance_tab_content')
                );
                return $tabs;
        }

这可以按照您的预期运行,并调用$woo_finance_tab_content。但是,我想将一些参数传递给$woo_finance_tab_content标签。这种情况可能吗?

4 个答案:

答案 0 :(得分:5)

woocommerce_product_tabs过滤器正在使用call_user_func函数来处理回调:

<?php foreach ( $tabs as $key => $tab ) : ?>
    <div class="panel entry-content wc-tab" id="tab-<?php echo esc_attr( $key ); ?>">
        <?php call_user_func( $tab['callback'], $key, $tab ); ?>
    </div>
<?php endforeach; ?>

实际上,它正在向回调发送两个参数:密钥(在您的情况下为finance_tab)和整个选项卡数组。所以,从理论上讲,你应该能够做到这一点:

$tabs['finance_tab'] = array(
    'title'     => __( 'Finance Options', 'woocommerce' ),
    'priority'  => 50,
    'callback'  => array ($this, 'woo_finance_tab_content'),
    'callback_parameters' => 'stuff'
);

然后:

function woo_finance_tab_content($tab_name, $tab) {
    echo $tab['callback_parameters']; // display "stuff"
}

答案 1 :(得分:1)

不幸的是没有。

像这样的回调中可用的参数只是回调定义的参数。

查看您想要的数据是否在传递给回调的参数中可用,因为它们通常是。

答案 2 :(得分:0)

好的,所以这是可能的(这有点hacky)。

正如@vard建议的那样宣告标签:

public function woo_finance_tab( $tabs ) {      
        if (is_product() && is_woocommerce() && $this->category_has_finance() == true)  {   
            $tabs['finance_tab'] = array(
                'title'     => __( 'Finance Options', 'woocommerce' ),
                'priority'  => 50,
                'callback'  => array ($this, 'woo_finance_tab_content' ),
                'callback_parameters' => array ($this, 'stuff')
                );
                return $tabs;
        }

现在在tab功能(I.E回调中定义的功能)中,执行以下操作:

public function woo_finance_tab_content($name,$tab_arr) {
     var_dump($tab_arr["callback_parameters"]["1"]);
}

var转储将显示“stuff”。这里显然没用,但这也可能是一个非常有用的数组。希望这对某人有用!

答案 3 :(得分:0)

我能够像这样传递数组作为参数:

function show_sizechart_tab( $tabs ) {
    global $post;

    $sizechart_image_ids = get_post_meta( $post->ID, 'sizechart_image_ids' );
    if ( count($sizechart_image_ids)>0 ){
        $tabs['sizechart_tab'] = array(
            'title'    => __( 'Size chart', 'woocommerce' ),
            'priority' => 10,
            'callback' => 'sizechart_product_tab_content',
            'image_ids'=> $sizechart_image_ids
        );
    }
    return $tabs;
}
function sizechart_product_tab_content($name, $tab_arr) {
print_r("<pre>");
print_r($tab_arr);
print_r("</pre>");

    echo '<h2>New Product Tab</h2>';
    echo '<p>Here\'s your new product tab.</p>';

}

tab_arr将具有image_ids

相关问题