1

I'm having trouble rewriting this line of code that contains create_function() in preparation for updating to PHP 8+.

The line of code to replace is:

add_action('widgets_init', create_function('', 'return register_widget("Ctxt_Menu_Widget");'));

I am trying to replace it with:

$callback = function(){
    ('', 'return register_widget("Ctxt_Menu_Widget");');
}
add_action('widgets_init', $callback);

But obviously, this isn't right, the replacement code won't allow the array withing that function.

Can someone help me rewrite this? Thanks so much!

2 Answers 2

1

The function should be a real (anonimous) function, sintactically valid in php, so it should be something like that

$callback = function(){
    return register_widget("Ctxt_Menu_Widget");
}

Then you can call this function

add_action('widgets_init', $callback);

Now wehn called, it is executed as a normal php functions

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Daniele, but what did work for me was as follows: add_action ( 'widgets_init', 'Ctxt_init_Menu_Widget' ); function Ctxt_init_Menu_Widget() { return register_widget('Ctxt_Menu_Widget'); }
It is exactly the same. You declare a function named Ctxt_init_Menu_Widget and call inside add_action. If you "put" the function inside a variable and use that variable, you should get the same results as per your solution. But, if you solved in that way, nopro, maybe this is a framework I don't know and this kind of solution doesn't work
-1

What turns out to be a good solution was:

add_action ( 'widgets_init', 'Ctxt_init_Menu_Widget' );
    function Ctxt_init_Menu_Widget() {
    return register_widget('Ctxt_Menu_Widget');
}

to replace:

add_action('widgets_init', create_function('', 'return register_widget("Ctxt_init_Menu_Widget");'));

Source: https://sarah-moyer.com/fix-create_function-deprecated-in-wordpress/

2 Comments

create_function() would return an anonymous function that's only ever used by reference. This code creates a new named function and this code will behave oddly in anything other than the global scope.
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.