1

I'm following the answer given for Add settings to menu items in the Customizer.

I'd like to inspect if a menu item is of type taxonomy. However, get_post_type returns nav_menu_item. How do I dig deeper?

    function customize_save_after($wp_customize)
    {
        foreach ( $wp_customize->settings() as $setting ) {
            if ( $setting instanceof WP_Customize_Nav_Menu_Item_Setting ) {
                $type = get_post_type($setting->post_id); // Returns 'nav_menu_item'.
                // How to retrieve the underlying type?
                $underlying_type = ....?

                if ($underlying_type !== 'taxonomy')
                {
                    return;
                }

                update_post_meta( $setting->post_id, '_my-custom-setting-field', (!empty( $setting->my_custom_setting_field) ) );
            }
        }
    }

2 Answers 2

1

It's easy to get the type of the menu item.

Just call the setting's value() method, which in the case of a nav menu item, would return an array with items like type (sample value: post_type or taxonomy) and object (sample value: post, page or category).

So in your case, just check whether the type's value is taxonomy.

$value           = $setting->value();
$underlying_type = is_array( $value ) ? $value['type'] : '';

/* Sample dump output of the $value array:
Array
(
    [menu_item_parent] => 0
    [object_id] => 1
    [object] => category
    [type] => taxonomy
    [type_label] => Category
    [url] => https://example.com/category/uncategorized/
    [title] => 
    [target] => 
    [attr_title] => 
    [description] => 
    [classes] => 
    [xfn] => 
    [position] => 3
    [status] => publish
    [original_title] => Uncategorized
    [nav_menu_term_id] => 89
    [_invalid] => 
)
*/
2
  • Unfortunately, that does not work at that point in the code. I found out I have to retrieve the unsanitized values.
    – Diana
    Commented Jul 15, 2023 at 5:27
  • 1
    That's strange, but I'm glad you found a solution.
    – Sally CJ
    Commented Jul 15, 2023 at 5:55
1

After going over the referenced question again, I noticed that some code was not pasted in the answer that was shared in the github gist. The way to access the values is:

$unsanitized_post_value = $setting->manager->unsanitized_post_values()[ $setting->id ];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.