2011-08-13 35 views
3

我想將$ extra變量傳遞給wordpress中的my_function。在以下的唯一途徑(定義全球)要做到這一點,還是有什麼更好的辦法來做到這一點.....將額外變量傳遞給掛鉤函數

global $extra; 
$extra = 'some value'; 
do_action('save_post','my_function' $post_ID); 

function my_function($post_ID) { 
    global $extra; 

/* other codes here*/ 
} 
+0

$ extra的值來自哪裏?也許有一種方法可以在函數內獲取這個值。 – migu

回答

0

你可以傳遞一個數組作爲參數來代替。不是最美麗的方式,但它會奏效。

$arg = array('extra'=>'some value', 'post_ID'=>$post_ID); 
do_action('save_post','my_function', $arg); 

function my_function($arg) { 
    $extra = $arg['extra']; 
    $post_ID = $arg['post_ID']; 

    /* other codes here*/ 
} 
0

有2種方法可以做到這一點:

  1. 定義一個全局變量,如果你正在做的動作是WordPress的內置。
  2. 如果該操作是您的自定義操作 - 則可以使用do_action('action_name', $arg1, $arg2)add_action($action_name, $callback_function, $priority, $arg_count)其中$arg_count是操作處理程序接受的參數數量。在大多數情況下,$priority應該是10。另請參閱http://codex.wordpress.org/Function_Reference/add_action