Carbon-fields: get_post_types() does not work in the field SET

Created on 27 Aug 2017  路  6Comments  路  Source: htmlburger/carbon-fields

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.

[type] question

Most helpful comment

It should run in the the admin_print_footer_scripts hook (when field data is prepared and passed as json).

All 6 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jonwaldstein picture jonwaldstein  路  3Comments

ittikorns picture ittikorns  路  3Comments

proweb picture proweb  路  3Comments

kaleidoscopique picture kaleidoscopique  路  3Comments

abdusfauzi picture abdusfauzi  路  3Comments