Hey. I need to get all types of posts using get_post_types () for the SET field. But Carbon Fields does not work on the 'init' hook. How can I solve the problem?
Now I type posts in the database, and then through get_option () I read and put in the SET field. This is inconvenient and un-dynamic.
Hi @campusboy87 ,
Passing a callable to the set_/add_options method will solve the problem for you. The callable will be executed lazily (which is another benefit by itself) so it will run after the init hook.
Sorry, but we could not understand your answer. Can you write an example? We tried to do so, but it did not work out:
Field::make( 'set', 'crb_product_features', 'Features' )
->add_options( apply_filters( 'product_features', [] ) )
add_action( 'init', function () {
add_filter( 'product_features', function ( $arr ) {
return get_post_types();
} );
} );
Here's an example of what I mean:
function my_options_function() {
$post_types = get_post_types( ... );
// filter $post_types array so it becomes a simple key=>value array of options
// e.g. array( 'post' => 'Post', 'page' => 'Page')
return array( ... );
}
Field::make( 'set', 'crb_product_features', 'Features' )
->add_options( 'my_options_function' )
Wow! It is so simple. Thank you! Unclear decision for me, the main thing is it works! :-) At what point does the function take place?
It should run in the the admin_print_footer_scripts hook (when field data is prepared and passed as json).
Thank you very much for your answers and your patience! If it is not difficult, enter this information in the documentation, please.
Most helpful comment
It should run in the the
admin_print_footer_scriptshook (when field data is prepared and passed as json).