Images attached to a CPT

Support MB Builder Images attached to a CPTResolved

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #38375
    JoeJoe
    Participant

    Hi,

    I am trying to get the following code to work, because I have a CPTs called 'pack' , which has a lot of attached images, I want to make the images shown on the admin edit screen.

    The following code works great, but only on post-type 'post', how can I change this to make it work on post-type 'pack'

    <?php
    add_filter( 'rwmb_meta_boxes', 'prefix_attached_images_meta_box' );
    function prefix_attached_images_meta_box( $meta_boxes ) {
    	$meta_boxes[] = array(
    		'title'  => esc_html__( 'Attached images', 'textdomain' ),
    		'fields' => array(
    			array(
    				'type'     => 'custom_html',
    				'callback' => 'prefix_get_images',
    			),
    		),
    	);
    	return $meta_boxes;
    }
    
    function prefix_get_images() {
    	$post_id = false;
    	if ( isset( $_GET['post'] ) ) {
    		$post_id = intval( $_GET['post'] );
    	} elseif ( isset( $_POST['post_ID'] ) ) {
    		$post_id = intval( $_POST['post_ID'] );
    	}
    	if ( ! $post_id ) {
    		return '';
    	}
    
    	$attachments = get_children( array(
    		'post_parent'    => $post_id,
    		'post_type'      => 'attachment',
    		'post_mime_type' => 'image',
    		'numberposts'    => - 1,
    		'post_status'    => 'any',
    	) );
    	if ( empty( $attachments ) ) {
    		return esc_html__( 'No images attached', 'textdomain' );
    	}
    	$output = '';
    	foreach ( $attachments as $attachment ) {
    		$output .= wp_get_attachment_image( $attachment->ID, 'thumbnail' );
    	}
    	return $output;
    }
    ?>
    #38382
    Long NguyenLong Nguyen
    Moderator

    Hi Joe,

    Please add the post_types setting when registering the meta box to display it on the CPT edit screen. Read more on the documentation https://docs.metabox.io/creating-fields-with-code/

    add_filter( 'rwmb_meta_boxes', 'prefix_attached_images_meta_box' );
    function prefix_attached_images_meta_box( $meta_boxes ) {
    	$meta_boxes[] = array(
    		'title'  => esc_html__( 'Attached images', 'textdomain' ),
    		'post_types'  => 'pack',
    		'fields' => array(
    			array(
    				'type'     => 'custom_html',
    				'callback' => 'prefix_get_images',
    			),
    		),
    	);
    	return $meta_boxes;
    }
Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.