add_action을 통해 인수를 함수에 전달할 수 있습니까?
내가 그런 일을 할 수 있을까? 내 직무에 대해 논쟁을 넘길 수 있을까?add_action doc를 이미 공부했지만 방법을 찾지 못했습니다.두 개의 인수를 전달하기 위한 정확한 구문은 어떻게 보일까요?특히 text 인수와 integer 인수를 전달하는 방법에 대해 설명합니다.
function recent_post_by_author($author,$number_of_posts) {
some commands;
}
add_action('thesis_hook_before_post','recent_post_by_author',10,'author,2')
갱신하다
do_action을 통해 어떻게든 이루어지는 것 같습니다만, 어떻게 하면 될까요? :-)
내가 그런 일을 할 수 있을까? 내 직무에 대해 논쟁을 넘길 수 있을까?
아니, 할 수 있어!문제는 실제로 어떤 종류의 함수를 add_action에 전달하고 do_action에서 무엇을 기대하는지에 있습니다.
- 'my_function_name'
- array( 인스턴스, 'instance_function_name')
- 'StaticClassName: a_function_on_static_class'
- 익명의
- 람다
- 닫힘
마무리로 할 수 있어요.
// custom args for hook
$args = array (
'author' => 6, // id
'posts_per_page'=> 1, // max posts
);
// subscribe to the hook w/custom args
add_action('thesis_hook_before_post',
function() use ( $args ) {
recent_post_by_author( $args ); });
// trigger the hook somewhere
do_action( 'thesis_hook_before_post' );
// renders a list of post tiles by author
function recent_post_by_author( $args ) {
// merge w/default args
$args = wp_parse_args( $args, array (
'author' => -1,
'orderby' => 'post_date',
'order' => 'ASC',
'posts_per_page'=> 25
));
// pull the user's posts
$user_posts = get_posts( $args );
// some commands
echo '<ul>';
foreach ( $user_posts as $post ) {
echo "<li>$post->post_title</li>";
}
echo '</ul>';
}
다음은 클로징 작업의 간단한 예입니다.
$total = array();
add_action('count_em_dude', function() use (&$total) { $total[] = count($total); } );
do_action ('count_em_dude' );
do_action ('count_em_dude' );
do_action ('count_em_dude' );
do_action ('count_em_dude' );
do_action ('count_em_dude' );
do_action ('count_em_dude' );
do_action ('count_em_dude' );
echo implode ( ', ', $total ); // 0, 1, 2, 3, 4, 5, 6
익명 vs.클로즈
add_action ('custom_action', function(){ echo 'anonymous functions work without args!'; } ); //
add_action ('custom_action', function($a, $b, $c, $d){ echo 'anonymous functions work but default args num is 1, the rest are null - '; var_dump(array($a,$b,$c,$d)); } ); // a
add_action ('custom_action', function($a, $b, $c, $d){ echo 'anonymous functions work if you specify number of args after priority - '; var_dump(array($a,$b,$c,$d)); }, 10, 4 ); // a,b,c,d
// CLOSURE
$value = 12345;
add_action ('custom_action', function($a, $b, $c, $d) use ($value) { echo 'closures allow you to include values - '; var_dump(array($a,$b,$c,$d, $value)); }, 10, 4 ); // a,b,c,d, 12345
// DO IT!
do_action( 'custom_action', 'aa', 'bb', 'cc', 'dd' );
프록시 함수 클래스
class ProxyFunc {
public $args = null;
public $func = null;
public $location = null;
public $func_args = null;
function __construct($func, $args, $location='after', $action='', $priority = 10, $accepted_args = 1) {
$this->func = $func;
$this->args = is_array($args) ? $args : array($args);
$this->location = $location;
if( ! empty($action) ){
// (optional) pass action in constructor to automatically subscribe
add_action($action, $this, $priority, $accepted_args );
}
}
function __invoke() {
// current arguments passed to invoke
$this->func_args = func_get_args();
// position of stored arguments
switch($this->location){
case 'after':
$args = array_merge($this->func_args, $this->args );
break;
case 'before':
$args = array_merge($this->args, $this->func_args );
break;
case 'replace':
$args = $this->args;
break;
case 'reference':
// only pass reference to this object
$args = array($this);
break;
default:
// ignore stored args
$args = $this->func_args;
}
// trigger the callback
call_user_func_array( $this->func, $args );
// clear current args
$this->func_args = null;
}
}
사용 예 #1
$proxyFunc = new ProxyFunc(
function() {
echo "<pre>"; print_r( func_get_args() ); wp_die();
},
array(1,2,3), 'after'
);
add_action('TestProxyFunc', $proxyFunc );
do_action('TestProxyFunc', 'Hello World', 'Goodbye'); // Hello World, 1, 2, 3
사용 예 #2
$proxyFunc = new ProxyFunc(
function() {
echo "<pre>"; print_r( func_get_args() ); wp_die();
}, // callback function
array(1,2,3), // stored args
'after', // position of stored args
'TestProxyFunc', // (optional) action
10, // (optional) priority
2 // (optional) increase the action args length.
);
do_action('TestProxyFunc', 'Hello World', 'Goodbye'); // Hello World, Goodbye, 1, 2, 3
대신:
add_action('thesis_hook_before_post','recent_post_by_author',10,'author,2')
다음 중 하나여야 합니다.
add_action('thesis_hook_before_post','recent_post_by_author',10,2)
...여기서 2는 인수 수이고 10은 함수를 실행하는 우선순위입니다.add_action에는 인수를 나열하지 않습니다.처음에는 이게 내 발목을 잡았다.그러면 기능은 다음과 같습니다.
function function_name ( $arg1, $arg2 ) { /* do stuff here */ }
add_action과 함수는 모두 함수에 들어갑니다.php 및 템플릿파일(페이지)에서 인수를 지정합니다.예를 들어 php)는 다음과 같이 do_action을 사용합니다.
do_action( 'name-of-action', $arg1, $arg2 );
이게 도움이 됐으면 좋겠다.
클래스와 함께 커스텀 WP 기능 구축
생성자를 사용하여 개체 변수를 설정하고 모든 클래스 메서드에서 사용할 수 있으므로 클래스에서 쉽게 수행할 수 있습니다.예를 들어 메타박스를 추가하는 방법은 다음과 같습니다.
// Array to pass to class
$data = array(
"meta_id" => "custom_wp_meta",
"a" => true,
"b" => true,
// etc...
);
// Init class
$var = new yourWpClass ($data);
// Class
class yourWpClass {
// Pass $data var to class
function __construct($init) {
$this->box = $init; // Get data in var
$this->meta_id = $init["meta_id"];
add_action( 'add_meta_boxes', array(&$this, '_reg_meta') );
}
public function _reg_meta() {
add_meta_box(
$this->meta_id,
// etc ....
);
}
}
__construct($arg)
와와 the와 function functionname($arg)
그러면 글로벌 변수를 피하고 클래스 객체의 함수에 필요한 모든 정보를 전달할 수 있습니다.
이러한 페이지는 워드프레스 메타/플러그인 작성 시 참고가 될 것으로 생각됩니다.->
데이터 add_action
- 를 통해서.
do_action
액션을 ) (스스로 액션을 작성하는 경우) wp_localize_script
access JavaScript에 가 있는 (JavaScript)- 「」를 사용합니다.
use
Closures Closures/Anonymous/Lamda - 화살표 기능 활용(PHP 7.4+)
add_filter
,apply_filters
global
★★★★★★★★★★★★★★★★★」$GLOBALS
set_transient
,get_transient
)
~ #1 ★★do_action
할 수 는, .do_action
:
/**
* Our client code
*
* Here we recieve required variables.
*/
function bar($data1, $data2, $data3) {
/**
* It's not necessary that names of these variables match
* the names of the variables we pass bellow in do_action.
*/
echo $data1 . $data2 . $data3;
}
add_action( 'foo', 'bar', 10, 3 );
/**
* The code where action fires
*
* Here we pass required variables.
*/
$data1 = '1';
$data2 = '2';
$data3 = '3';
//...
do_action( 'foo', $data1, $data2, $data3 /*, .... */ );
#2wp_localize_script
JavaScript에 변수를 전달해야 하는 경우 이것이 가장 좋은 방법입니다.
기능들.php
/**
* Enqueue script
*/
add_action( 'wp_enqueue_scripts', function() {
wp_enqueue_script( 'my_script', get_template_directory_uri() . '/assets/js/my-script.js', array( 'jquery' ), false, false );
} );
/**
* Pass data to the script as an object with name `my_data`
*/
add_action( 'wp_enqueue_scripts', function(){
wp_localize_script( 'my_script', 'my_data', [
'bar' => 'some data',
'foo' => 'something else'
] );
} );
my-script.my-script.my-script
alert(my_data.bar); // "some data"
alert(my_data.foo); // "something else"
기본적으로 동일하지만 없음wp_localize_script
:
기능들.php
add_action( 'wp_enqueue_scripts', function(){
echo <<<EOT
<script>
window.my_data = { 'bar' : 'somedata', 'foo' : 'something else' };
</script>;
EOT;
wp_enqueue_script( 'my_script', get_template_directory_uri() . '/assets/js/my-script.js', array( 'jquery' ), false, false );
}, 10, 1 );
사용방법 #3 사용방법use
Closures Closures/Anonymous/Lamda
액션이 기동하는 코드에 액세스 할 수 없는 경우는, 다음과 같이 데이터를 슬립 할 수 있습니다(PHP 5.3+).
$data1 = '1';
$data2 = '2';
$data3 = '3';
add_action( 'init', function() use ($data1, $data2, $data3) {
echo $data1 . $data2 . $data3; // 123
});
#4 화살표 기능 활용(PHP 7.4+)
는 상위 간결합니다.use
:
$data1 = '1';
$data2 = '2';
$data3 = '3';
add_action( 'init', fn() => print( $data1 . $data2 . $data3 ) ); // prints "123"
사용#5 ★★add_filter
,apply_filters
는 이 함수로 수 .add_filter
됩니다.apply_filters
:
/**
* Register the data with the filter functions
*/
add_filter( 'data_1', function() { return '1'; } );
add_filter( 'data_2', function() { return '2'; } );
add_filter( 'data_3', fn() => '3' ); // or in concise way with arrow function
function foo() {
/**
* Get the previously registered data
*/
echo apply_filters( 'data_1', null ) .
apply_filters( 'data_2', null ) .
apply_filters( 'data_3', null ); // 123
}
add_action( 'init', 'foo');
많은 플러그인에서 이 방법을 사용해 왔습니다.
를 #6으로 global
★★★★★★★★★★★★★★★★★」$GLOBALS
way (키디 웨이
되지 않는 는, 「 를 사용해 주세요.global
예 1:
$data1 = '1';
$data2 = '2';
$data3 = '3';
function foo() {
global $data1, $data2, $data3;
echo $data1 . $data2 . $data3; // 123
}
add_action( 'init', 'foo' );
예 #2 사용방법$GLOBALS
global
$data1 = '1';
$data2 = '2';
$data3 = '3';
function foo() {
echo $GLOBALS['data1'] . $GLOBALS['data2'] . $GLOBALS['data3']; // 123
}
add_action( 'init', 'foo' );
사용#7 ★★set_transient
,get_transient
,set_query_var
,get_query_var
예 1: 폼을 인쇄하는 쇼트코드가 있으며, 폼에서 전송된 데이터는 AJAX를 통해 전송되어 처리됩니다.또, 쇼트코드 파라미터로부터 취득할 필요가 있는 E-메일로 송신됩니다.
- 단축코드 초기화
- 쇼트코드 해석 및 인쇄, 과도기 파라미터 기억
--- Ajax 핸들러 내 ---
- 임시에서 필요한 매개 변수를 가져와 전자 메일을 보냅니다.
예 2: Wordpress 5.5가 출시되기 전에 일부 사용자는 다음 중 하나의 매개 변수를 전달했습니다.wp_query
타타에 get/set_query_vars
템플릿 부품에 전달하기 위해 이러한 부품도 사용할 수 있습니다.
섞어서 사용하세요.건배.
으로는, 「 」입니다.do_action
는 액션을 실행해야 하는 위치에 배치되며 이름과 커스텀 파라미터가 필요합니다.
사용하여 는 add_action의 합니다.do_action()
첫 번째 인수로, 두 번째 인수로 함수 이름을 지정합니다.예를 들어 다음과 같습니다.
function recent_post_by_author($author,$number_of_posts) {
some commands;
}
add_action('get_the_data','recent_post_by_author',10,'author,2');
여기서 실행이 됩니다.
do_action('get_the_data',$author,$number_of_posts);
잘 될 거야
vars를 합니다.fn
번째 째번:
$fn = function() use($pollId){
echo "<p>NO POLLS FOUND FOR POLL ID $pollId</p>";
};
add_action('admin_notices', $fn);
PHP 5.3+에서는 closure를 사용하고 있습니다.그러면 디폴트값을 통과시켜 글로벌 없이 내 값을 통과시킬 수 있습니다.(add_filter의 경우)
...
$tt="try this";
add_filter( 'the_posts', function($posts,$query=false) use ($tt) {
echo $tt;
print_r($posts);
return $posts;
} );
이건 오래됐지만, 받아들여진 답이 없어요.구글 검색자들이 희망을 가질 수 있도록 부활하는 것.
이미 존재하는 경우add_action
다음과 같은 인수를 받아들이지 않는 콜:
function my_function() {
echo 100;
}
add_action('wp_footer', 'my_function');
다음과 같이 어나니머스 함수를 콜백으로 사용함으로써 인수를 해당 함수에 전달할 수 있습니다.
function my_function($number) {
echo $number;
}
$number = 101;
add_action('wp_footer', function() { global $number; my_function($number); });
사용 사례에 따라 다른 형식의 콜백을 사용해야 할 수도 있습니다.또, 경우에 따라서는 적절히 선언된 함수를 사용할 수도 있습니다.또한 범위에 문제가 발생할 수 있습니다.
저도 오늘 같은 일을 겪었습니다.여기 있는 모든 답변은 불분명하거나 무관하거나 과도하기 때문에간단한 답변을 드리려고 합니다.
여기서 가장 일반적인 답변이 이미 언급되어 있듯이, 원하는 작업을 수행하려면 익명 기능을 사용해야 합니다.그러나 IMO에 특히 주목할 필요가 있는 것은 사용 가능한 동작 파라미터를 기능에 전달하는 이점입니다.
어딘가에 있는 경우 액션훅은 다음과 같이 정의됩니다.
do_action('cool_action_name', $first_param, $second_param);
의 값을 전달할 수 있습니다.$first_param
그리고.$second_param
다음과 같이 자신의 기능을 추가하고 자신의 매개 변수를 추가합니다.
add_action('cool_action_name',
function ($first_param, $second_param) {
// Assuming you're working in a class, so $this is the scope.
$this->your_cool_method($first_param, $second_param, 'something_else');
}
);
그런 다음 메서드의 모든 값을 다음과 같이 사용할 수 있습니다.
public function your_cool_method($first_param, $second_param, $something_else)
{
// Do something with the params.
}
Wordpress 플러그인은 오래전에 썼지만 Wordpress Codex에 접속해서 가능한 일이라고 생각합니다.http://codex.wordpress.org/Function_Reference/add_action
<?php add_action( $tag, $function_to_add, $priority, $accepted_args ); ?>
배열로 넘겨주셔야 할 것 같아요.예를 들어 "인수를 받아들인다"를 살펴보세요.
안녕.
저는 같은 문제에 부딪혀서 글로벌 변수를 사용하여 해결했습니다.다음과 같은 경우:
global $myvar;
$myvar = value;
add_action('hook', 'myfunction');
function myfunction() {
global $myvar;
}
약간 엉성하지만 효과가 있다.
다음과 같이 단순하지 않은 이유:
function recent_post_by_author_related($author,$number_of_posts) {
// some commands;
}
function recent_post_by_author() {
recent_post_by_author_related($foo, $bar);
}
add_action('thesis_hook_before_post','recent_post_by_author')
내년에 이걸 검색할 때 이걸 어디서 찾을 수 있는지 알 수 있도록 여기에 이걸 추가하고 싶었어요.이는 최신 WordPress 문서에서 수정한 것입니다.
다음은 WordPress의 설명서에서 이를 수행하는 방법입니다.
// The action callback function.
function example_callback( $arg1, $arg2 ) {
// (maybe) do something with the args to get a value.
return $value;
}
add_action( 'example_action', 'example_callback', 10, 2 );
// the 2 above specifies the number of args
/*
* Trigger the actions by calling the 'example_callback()' function
* that's hooked onto `example_action` above.
*
* - 'example_action' is the action hook.
* - $arg1 and $arg2 are the additional arguments passed to the callback.
*/
$value = do_action( 'example_action', $arg1, $arg2 );
do_action 대신 파라미터를 호출 가능한 함수에 전달할 경우 익명 함수를 호출할 수 있습니다.예:
// Route Web Requests
add_action('shutdown', function() {
Router::singleton()->routeRequests('app.php');
});
보이시죠?do_action('shutdown')
파라미터는 받지 않습니다만,routeRequests
한다.
하다
function reset_header() {
ob_start();
}
add_action('init', 'reset_header');
그리고나서
reset_header();
wp_redirect( $approvalUrl);
자세한 것은, https://tommcfarlin.com/wp_redirect-headers-already-sent/ 를 참조해 주세요.
파라미터와 프로세스를 송신하기 위한 코드를 작성했습니다.
function recibe_data_post() {
$post_data = $_POST;
if (isset($post_data)) {
if (isset($post_data['lista_negra'])) {
$args = array (
'btn' => 'lista_negra',
'estado'=> $post_data['lista_negra'],
);
add_action('template_redirect',
function() use ( $args ) {
recibe_parametros_btn( $args ); });
}
if (isset($post_data['seleccionado'])) {
$args = array (
'btn' => 'seleccionado',
'estado'=> $post_data['seleccionado'],
);
add_action('template_redirect',
function() use ( $args ) {
recibe_parametros_btn( $args ); });
}
}
}
add_action( 'init', 'recibe_data_post' );
function recibe_parametros_btn( $args ) {
$data_enc = json_encode($args);
$data_dec = json_decode($data_enc);
$btn = $data_dec->btn;
$estado = $data_dec->estado;
fdav_procesa_botones($btn, $estado);
}
function fdav_procesa_botones($btn, int $estado) {
$post_id = get_the_ID();
$data = get_post($post_id);
if ( $estado == 1 ) {
update_field($btn, 0, $post_id);
} elseif ( $estado == 0 ) {
update_field($btn, 1, $post_id);
}
}
언급URL : https://stackoverflow.com/questions/2843356/can-i-pass-arguments-to-my-function-through-add-action
'source' 카테고리의 다른 글
IE에서 jQuery ajax 호출과 함께 '전송 불가' 오류 발생 (0) | 2023.03.10 |
---|---|
jquery $.get()을 사용하여 파라미터를 송신하는 방법 (0) | 2023.03.10 |
Fetch Post 콜 후 리다이렉트 (0) | 2023.03.10 |
Json을 사용하여 두 가지 데이터 유형이 될 수 있는 JSON 속성을 역직렬화하는 방법.그물 (0) | 2023.03.10 |
배열별로 정렬된 ID 배열을 가진 WP_쿼리 (0) | 2023.03.10 |