Viewing 14 replies - 1 through 14 (of 14 total)
  • Hi, can you share the minimal version of the code necessary to reproduce the problem?

    If you have WP-CLI installed, you can try using wp term recount. If that works, try assigning a term from the taxonomy to a new post, and see if the count updates correctly.

    Thread Starter sacconi

    (@sacconi)

    // CREAZIONE TASSONOMIA OSPITI
    
    add_action( 'init', function() {
        $labels = array(
            'name'              => _x( 'Ospiti', 'taxonomy general name' ),
            'singular_name'     => _x( 'Ospite', 'taxonomy singular name' ),
        );
        register_taxonomy( 'numero_ospiti', array( 'post' ), array(
            'hierarchical'      => false,
            'labels'            => $labels,
    'meta_box_cb'       => "post_categories_meta_box",
    'show_admin_column'  => true,
     'public'            => true,
            
        ) );
    } );
    
    add_action( 'admin_head', function() {
        ?>
        <style type="text/css">
            #newtaxonomy_name_parent {
                display: none;
            }
        </style>
        <?php
    });
    add_action( 'admin_init', function() {
        if( isset( $_POST['tax_input'] ) && is_array( $_POST['tax_input'] ) ) {
            $new_tax_input = array();
            foreach( $_POST['tax_input'] as $tax => $terms) {
                if( is_array( $terms ) ) {
                  $taxonomy = get_taxonomy( $tax );
                  if( !$taxonomy->hierarchical ) {
                      $terms = array_map( 'intval', array_filter( $terms ) );
                  }
                }
                $new_tax_input[$tax] = $terms;
            }
            $_POST['tax_input'] = $new_tax_input;
        }
    });
    
    /**
     * Register tax_input[numero_ospiti] field if you want it
     * to be available via WordPress REST API.
     */
    function register_tax_input_ospiti() {
        \register_meta(
            'post',
            'tax_input[numero_ospiti]',
            array(
                'object_subtype'    => 'post',
                'description'       => 'Count of guests.',
                'single'            => true,
                'type'              => 'integer',
                'show_in_rest'      => array(
                    'schema' => array(
                        'type'  => 'integer'
                    )
                ),
                'default'           => 0,
                'sanitize_callback' => function( $value ) { return $value; },
                'auth_callback'     => function() { return '__return_true'; }
            )
        );
    }
    
    
    //creating a META BOX OSPITI
    function custom_meta_box_markup( $post ) {
        $post_id = $post->ID;
    
        // tax_input[numero_ospiti] is an array,
        // but managed as a single value.
        $is_single_value = true;
    
        // Retrieve the term name that was saved to the database.
        $selected_term_name = get_post_meta( $post_id, 'tax_input[numero_ospiti]', $is_single_value );
        $terms = get_terms( array(
            'taxonomy' => 'numero_ospiti',
            'fields'   => 'id=>name',
            'hide_empty' => false,
            'number'   => 0
           
        ) );
    
        $flipped_terms = array_flip( $terms );
        if ( isset( $flipped_terms[ $selected_term_name ] ) ) {
            $selected_term_id = $flipped_terms[ $selected_term_name ];
        } else {
            $selected_term_id = 0;
        }
    
        $set_referer_field = true;
        $echo_html = false;
        $wp_nonce_html = wp_nonce_field(
            basename( __FILE__ ),
            'meta-box-nonce',
            $set_referer_field,
            $echo_html
        );
    
        $args = array(
            'show_option_none'  => ' ',
            'taxonomy'   => 'numero_ospiti',
            'selected'   => $selected_term_id,
            'name'       => 'tax_input[numero_ospiti]',
            'hide_empty' => false,
            'echo'       => false
        );
        $dropdown_cat_html = wp_dropdown_categories( $args );
    
        $html = <<<EOHTML
        <div>
            $wp_nonce_html
            <label for="meta-box-ospiti">N.ospiti</label>
            $dropdown_cat_html
        </div>
        EOHTML;
    
        echo $html;
    }
    
    function add_custom_meta_box() {
        add_meta_box(
            'demo-meta-box',          // Unique ID.
            'Ospiti',                 // Meta box title.
            'custom_meta_box_markup', // Content callback, must be of type callable.
            'post',                   // Screen type.
            'side'                    // Context: where meta box should display in the screen.
        );
    }
    add_action( 'add_meta_boxes', 'add_custom_meta_box' );
    
    /**
     * Update post meta data.
     *
     * @param int $post_id Post ID of post being saved.
     */
    function save_custom_meta_box( $post_id ) {
        if (
            isset( $_POST ) &&
            isset( $_POST['tax_input'] ) &&
            isset( $_POST['tax_input']['numero_ospiti'] )
        ) {
            $term_id = $_POST['tax_input']['numero_ospiti'];
            $terms = get_terms( array(
                'taxonomy'   => 'numero_ospiti',
                'fields'     => 'id=>name',
                'hide_empty' => false,
                'number'     => 0
               ) );
            $selected_term_name = $terms[ $term_id  ];
    
            update_post_meta(
                $post_id,
                'tax_input[numero_ospiti]',
                 $selected_term_name
            );
        }
    }
    add_action( 'save_post', 'save_custom_meta_box' );
    

    When I try to save a post with that code I get the following in my error log, and the HTTP request to save the post meta fails with a 500 error.

    PHP Fatal error: Uncaught TypeError: array_map(): Argument #2 ($array) must be of type array, string given in wp-admin/includes/post.php:2149

    Stack trace:

    #0 wp-admin/includes/post.php(2149): array_map(‘intval’, ‘4’)

    #1 wp-admin/includes/post.php(436): taxonomy_meta_box_sanitize_cb_checkboxes(‘numero_ospiti’, ‘4’)

    #2 wp-admin/post.php(227): edit_post()

    #3 {main}

    thrown in wp-admin/includes/post.php on line 2149

    Do you see any errors in your PHP log? Do all of the HTTP requests in your browser network console return a 200 (success) code?

    Make sure you have WP_DEBUG turned on in your dev environment.

    If you’re also getting that error, then it sounds like you need to make ['tax_input']['numero_ospiti'] an array of term IDs, rather than just an integer (even if the array only contains one item). I think that’s because normally multiple categories can be assigned, so the API handler that saves the categories expects an array.

    Another approach would be to specify a custom meta_box_sanitize_cb function when calling register_taxonomy().

    Thread Starter sacconi

    (@sacconi)

    When I save a post I cant see any error, look at this page: https://test.sacconicase.com/ , you’ll see an icon under the pics, a person with a number nearby, this represents the number of guests , meta key= numero_ospiti , so the meta key is working fine, the posts are loaded and saved, I dont know where I should see, I have a plugin : “Query monitor”, can I do something with it? What I have to do? thank you

    I’m not sure if Query Monitor would show it. The best way is to look at your PHP log file, after making sure that WP_DEBUG is enabled and saving the post.

    There’s some documentation at https://developer.www.ads-software.com/advanced-administration/debug/debug-wordpress/. You can use phpinfo() to see where your error log is if you’re not sure.

    Thread Starter sacconi

    (@sacconi)

    Maybe can I use a plugin to detect a code-bug and operate a debugging? I have found WP Debugging

    It sounds like that plugin will let you view your PHP log file, so that works too.

    Thread Starter sacconi

    (@sacconi)

    I installed Wp Debugging, the plugin asked me to activate Query Monitor (it was deactivated), I went to the home page of my website and got 1 message of error: https://ibb.co/f8wsGgp , what I have to do?

    That one seems unrelated. Can you try saving a post again and see if you get errors then? The editor saves the post using a API request in the background, so you won’t see the error in the editor. You’ll need to use your browser’s Developer Tools console to look at the network requests, and see the response of the request.

    If that plugin has a place where it shows you the PHP log, then you could also look there to see if any new errors were added from the request.

    Thread Starter sacconi

    (@sacconi)

    if wp debugging and/or Query monitor are activated I cant edit any post, I receive an error message: “Publishing is failed. The response is not a valid JSON response”

    That probably means that you’ll also getting the error the I encountered. I’d recommend trying the solutions I recommended there, and see if that fixes it.

    Thread Starter sacconi

    (@sacconi)

    I deleted this in my taxonomy function: ‘meta_box_cb’       => “post_categories_meta_box”,

    now the taxonomy is displaying a count but with wrong values..I mean it reads other meta value but not what I select in my custom field in the post editor and not what users should see

    https://ibb.co/XX8dY6D

    Any idea?

    I think you can restore the meta_box_cb line you had earlier, and then add this line to register_taxonomy():

    meta_box_sanitize_cb => 'sanitize_meta_box_cb_ospiti'

    Then create a function with that name, and have it sanitize the values that were passed.

    You can look at taxonomy_meta_box_sanitize_cb_checkboxes() and taxonomy_meta_box_sanitize_cb_input() as examples, but you’ll need to make it match the same data structure/format that your other code uses.

    Thread Starter sacconi

    (@sacconi)

    Thank you, I’ll try to do it. In the meanwhile I generated a taxonomy code by a plugin, I wanted to have your opinion. The count of taxonomy values in admin is working, but the code seems to be redundant, it seems 2 identical codes for the same taxonomy. It seems also fit for only one theme (sacconicase)

    function cptui_register_my_taxes() {
    
        /**
         * Taxonomy: Tipologia.
         */
    
        $labels = [
            "name" => esc_html__( "Tipologie", "sacconicase" ),
            "singular_name" => esc_html__( "Tipologia", "sacconicase" ),
        ];
    
        
        $args = [
            "label" => esc_html__( "Tipologie", "sacconicase" ),
            "labels" => $labels,
            "public" => true,
            "publicly_queryable" => true,
            "hierarchical" => false,
            "show_ui" => true,
            "show_in_menu" => true,
            "show_in_nav_menus" => true,
            "query_var" => true,
            "rewrite" => [ 'slug' => 'tipologia', 'with_front' => true, ],
            "show_admin_column" => false,
            "show_in_rest" => true,
            "show_tagcloud" => false,
            "rest_base" => "tipologia",
            "rest_controller_class" => "WP_REST_Terms_Controller",
            "rest_namespace" => "wp/v2",
            "show_in_quick_edit" => false,
            "sort" => false,
            "show_in_graphql" => false,
            "meta_box_cb" => "post_tags_meta_box",
        ];
        register_taxonomy( "tipologia", [ "post" ], $args );
    }
    add_action( 'init', 'cptui_register_my_taxes' );
    
    
    function cptui_register_my_taxes_tipologia() {
    
        /**
         * Taxonomy: Tipologie.
         */
    
        $labels = [
            "name" => esc_html__( "Tipologie", "sacconicase" ),
            "singular_name" => esc_html__( "Tipologia", "sacconicase" ),
        ];
    
        
        $args = [
            "label" => esc_html__( "Tipologie", "sacconicase" ),
            "labels" => $labels,
            "public" => true,
            "publicly_queryable" => true,
            "hierarchical" => false,
            "show_ui" => true,
            "show_in_menu" => true,
            "show_in_nav_menus" => true,
            "query_var" => true,
            "rewrite" => [ 'slug' => 'tipologia', 'with_front' => true, ],
            "show_admin_column" => false,
            "show_in_rest" => true,
            "show_tagcloud" => false,
            "rest_base" => "tipologia",
            "rest_controller_class" => "WP_REST_Terms_Controller",
            "rest_namespace" => "wp/v2",
            "show_in_quick_edit" => false,
            "sort" => false,
            "show_in_graphql" => false,
            "meta_box_cb" => "post_tags_meta_box",
        ];
        register_taxonomy( "tipologia", [ "post" ], $args );
    }
    add_action( 'init', 'cptui_register_my_taxes_tipologia' );
    
    
Viewing 14 replies - 1 through 14 (of 14 total)
  • The topic ‘count of custom taxonomies not working’ is closed to new replies.