• Hello, I want to create metaboxes in foreach loop. The requirement is, I have an array of custom post types and I want to run a loop to add metaboxes for the post types that are as a key in an array.
    So far I have developed much of the requirement but now I am stuck in the part where callback function inside add_meta_box() is to be called. I have used call_user_func_array to call the callback function and pass the $key as an argument but it is returning error and its not working. Below is my code:

    
    	 function rttk_create_boxes(){
    		$myarray = $this->rttk_get_posttype_array();
    		foreach ($myarray as $key => $value) {
    			// echo "key--".$key;
    			// $arr[] = '';
    			// $arr[] = $key;
    			$key = (array)$key;
    			add_meta_box(
    				'rttk_'.end($key).'_id',
    				__( 'Details', 'rara-theme-toolkit-pro' ),
    				//array($this,'rttk_testimonials_metabox_callback',$key),
    				call_user_func_array(array( $this, 'rttk_testimonials_metabox_callback'),$key ),
    				$key,
    				'side',
    				'high'
    			);
    		}
    	}
    
    	// testimonials template form
    	public function rttk_testimonials_metabox_callback($key){
    		// $myarray = $this->rttk_get_posttype_array();
    		// foreach ($myarray as $key => $value) {
    			include RTTKPRO_BASE_PATH.'/includes/meta-parts/rttk-'.$key.'-template.php';
    		// }
    	}
    

    Any help would be highly appreciated.
    Thanks!

    • This topic was modified 7 years, 6 months ago by Jan Dembowski.
Viewing 1 replies (of 1 total)
  • the function declaration says,

    add_meta_box( string $id, string $title, callable $callback, string|array|WP_Screen $screen = null, string $context = 'advanced', string $priority = 'default', array $callback_args = null )

    Notice the last parameter $callback_args. You can pass an array as callback args.

    function rttk_create_boxes(){
    	$myarray = $this->rttk_get_posttype_array();
    	foreach ($myarray as $key => $value) {
    		add_meta_box(
    			'rttk_'.$key.'_id', //assuming each key is different
    			__( 'Details', 'rara-theme-toolkit-pro' ),
    			array($this,'rttk_testimonials_metabox_callback'),
    			$screen, // WP_Screen
    			'side',
    			'high',
    			array('key' => $key), // This is what you need
    		);
    	}
    }
    
    public function rttk_testimonials_metabox_callback( $post, $callback_args ){
    	$key = $callback_args['args']['key'];
    	include RTTKPRO_BASE_PATH.'/includes/meta-parts/rttk-'.$key.'-template.php';
    }
    

    See if this is working.

Viewing 1 replies (of 1 total)
  • The topic ‘Creating metaboxes in loop’ is closed to new replies.