• Resolved cheerychops

    (@cheerychops)


    I am trying to create a custom metabox in the edit post screen – specifically a WooCommerce product post. The box is created ok but saving and recalling the meta data fails and I cannot see why 🙁

    /*
    Plugin Name: WIZ Custom Meta Box Plugin
    Plugin URI: 
    Description: 
    Version: 1.0
    Author: David
    Author URI:
    License:
    */
    add_action( 'add_meta_boxes', 'wizpart_meta_box_init' );
    
    // meta box functions for adding the meta box and saving the data
    function wizpart_meta_box_init() {
    
        // create our custom meta box
        add_meta_box( 'wizpart_meta', 'Parts Information', 'wizpart_meta_box', 'product', 'normal', 'high' );
    
    }
    
    function wizpart_meta_box( $post ) {
    
        // retrieve the custom meta box values
        $wizpart_meta = get_post_meta( $post->ID, '_wizpart_data');
    	// Debug $wizpart_meta = array("sku"=>"GA1", "quant"=>"6");
      
      	echo var_dump($wizpart_meta);
      
    	$wizpart_sku = (! empty( $wizpart_meta[0]))? $wizpart_meta[0] : 'NA';
    	$wizpart_quant = (! empty( $wizpart_meta[1]))? $wizpart_meta[1] : 'NA';
    	
        //nonce for security
    	wp_nonce_field( 'meta_box_save', 'wizpart_plugin' );
    
       // display stored values 
    	echo '<table>';
    	echo '<tr>';
    	echo '<td> SKU: </td>';
    	echo '<td> <input type="text" name="wizpart[sku]" value = "'.esc_attr( $wizpart_sku ).'" size="5" > </td>';
    	echo '</tr>';
    	
    	echo '<tr>';
    	echo '<td> Quant: </td>';
    	echo '<td> <input type="text" name="wizpart[quant]" value = "'.esc_attr( $wizpart_quant ).'" size="5" > </td>';
    	echo '</tr>';
    	echo '</table>';
    
    }
    
    // hook to save our meta box data when the post is saved
    add_action( 'save_post', 'wizpart_save_meta_box' );
    
    function wizpart_save_meta_box( $post_id ) {
    
        // process form data if $_POST is set
     	  	
    
    		// if auto saving skip saving our meta box data
    		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
    			return;
    		echo "<h2>PHP is Fun!</h2>";
    		//check nonce for security
    		wp_verify_nonce( 'meta_box_save', 'wizpart_plugin' );
    		// store data in an array
    		$wizpart_data = $POST['wizpart'];
    		// use array map function to sanitize options
    		$wizpart_data = array_map( 'sanitize_text_field', $wizpart_data) ;
    
            // save the meta box data as post meta using the post ID as a unique prefix
            // using add_post_meta to increment the array with values
    	  foreach( $wizpart_data as $value ) {
        	echo $value;
    		add_post_meta( $post_id, '_wizpart_data',  $value );
    		}
    	}
    

    The ‘PHP is Fun!’ line is not displayed. No data is entered under ‘_wizpart_data’ in the DB. Any ideas – I am relatively new to PHP

    • This topic was modified 2 months, 1 week ago by cheerychops.
Viewing 5 replies - 1 through 5 (of 5 total)
  • Oh there is quite a bit wrong

    First don’t try to echo inside the save_post hook – if you want to debug and are not usimng a proper IDE with XDEBUG then use error_log(‘messegae’) but seriously get an IDE such as VSCODE and workout how to do xdebug step debugging, use a local dev environment.

    Also ture WP_DEDUG on.

    Second

    $wizpart_data = $POST['wizpart'];

    should be

    $wizpart_data = $_POST['wizpart'];

    then

    foreach( $wizpart_data as $value ) {
        	echo $value;
    		add_post_meta( $post_id, '_wizpart_data',  $value );
    		}

    OK you understand _wizpart_data is an array

    so that code loops through each element of the array and each time overwrites tme meta data – which means you end up with the last string not and array

    this whole section should be simply

    add_post_meta( $post_id, '_wizpart_data', $wizpart_data );

    as add_post_meta handle teh serialization of arrays and objects

    Fix those and you should be closer

    • This reply was modified 2 months, 1 week ago by Alan Fuller.
    Thread Starter cheerychops

    (@cheerychops)

    Thank you!

    Saving into the array is working fine. I am not picking up the meta data as I probably have not understood how to extract from this array – which I need to do to display the previous entered meta data and to delete it if necessary.

    array(3) { [0]=> array(2) { [“sku”]=> string(3) “GA1” [“quant”]=> string(1) “6” } [1]=> array(2) { [“sku”]=> string(3) “GA1” [“quant”]=> string(1) “6” } [2]=> array(2) { [“sku”]=> string(3) “GA1” [“quant”]=> string(1) “6” } }

    I have also made a local installation for testing. I use Notepad++ which has an extension for the XDEBUG so I will look into that.

    Alan Fuller

    (@alanfuller)

    looking

    Alan Fuller

    (@alanfuller)

    It is an associative array so referenced

    the $_POST should be an array equivalent to

    $wizpart_data = array ( 'sku' => 'value', 'quant' => 'another value' );

    an saving an retriving the meta should retrive the same

    to access

    you would via the associative key rather than the index / position

    $wizpart_sku = (! empty( $wizpart_meta['sku']))? $wizpart_meta['sku'] : 'NA';
    	$wizpart_quant = (! empty( $wizpart_meta['quant']))? $wizpart_meta['quant'] : 'NA';

    see also https://www.w3schools.com/php/php_arrays_associative.asp

    Thread Starter cheerychops

    (@cheerychops)

    Thanks for your continuing patience!

    This is the current code. It displays the first value using the ‘reset()’ function (bold) other wise it displays ‘NA’. Is this the best way to access the ‘nth’ entry in an associative 2D array?

    Also I used the ‘add_post_meta’ (bold) function as the update overwrites the data – is this correct.

    <?php
    
    // Meta Box Inventory Project
    
    
    /*
    Plugin Name: WIZ Custom Meta Box Plugin
    Plugin URI: 
    Description: 
    Version: 1.0
    Author: David
    Author URI:
    License:
    */
    add_action( 'add_meta_boxes', 'wizpart_meta_box_init' );
    
    // meta box functions for adding the meta box and saving the data
    function wizpart_meta_box_init() {
    
        // create our custom meta box
        add_meta_box( 'wizpart_meta', 'Parts Information', 'wizpart_meta_box', 'product', 'normal', 'high' );
    
    }
    
    function wizpart_meta_box( $post ) {
    
        // retrieve the custom meta box values
        $wizpart_meta = reset(get_post_meta( $post->ID, '_wizpart_data'));
    	
      	// debug
      	echo var_dump($wizpart_meta);
      
    	$wizpart_sku = (! empty( $wizpart_meta['sku'])) ? $wizpart_meta['sku'] : 'NA';
    	$wizpart_quant = (! empty( $wizpart_meta['quant'])) ? $wizpart_meta['quant'] : 'NA';
    	
    	
        //nonce for security
    	wp_nonce_field( 'meta_box_save', 'wizpart_plugin' );
    
       // display stored values 
    	echo '<table>';
    	echo '<tr>';
    	echo '<td> SKU: </td>';
    	echo '<td> <input type="text" name="wizpart[sku]" value = "'.esc_attr( $wizpart_sku ).'" size="5" > </td>';
    	echo '</tr>';
    	
    	echo '<tr>';
    	echo '<td> Quant: </td>';
    	echo '<td> <input type="text" name="wizpart[quant]" value = "'.esc_attr( $wizpart_quant ).'" size="5" > </td>';
    	echo '</tr>';
    	echo '</table>';
    
    }
    
    // hook to save our meta box data when the post is saved
    add_action( 'save_post', 'wizpart_save_meta_box' );
    
    function wizpart_save_meta_box( $post_id ) {
    
        // process form data if $_POST is set
     	  	
    
    		// if auto saving skip saving our meta box data
    		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
    			return;
    		//check nonce for security
    		wp_verify_nonce( 'meta_box_save', 'wizpart_plugin' );
    		// store data in an array
    		$wizpart_data = $_POST['wizpart'];
    		// use array map function to sanitize options
    		$wizpart_data = array_map( 'sanitize_text_field', $wizpart_data) ;
    
            // save the meta box data as post meta using the post ID as a unique prefix
            // using add_post_meta to increment the array with values
    		add_post_meta( $post_id, '_wizpart_data', $wizpart_data );
    	}
    ?>

    • This reply was modified 2 months ago by cheerychops. Reason: minor edit
    • This reply was modified 2 months ago by cheerychops. Reason: minor edit
Viewing 5 replies - 1 through 5 (of 5 total)
  • You must be logged in to reply to this topic.