0

I have create a carrousel and display it with shortcode and passed the image and text as attributes. However, the shortcode end up being to hard to read and edit when needed. Not user friendly.

[lytbox_carousel type="1" imagesid="68/|/ 66/|/ 63/|/ 61" headings="This is a Heading/|/ This is a Heading /|/ This is a Heading /|/ This is a Heading " texts="Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusamus illum quam quod reprehenderit possimus dolor ut magnam nesciunt, eos excepturi./|/ Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusamus illum quam quod reprehenderit possimus dolor ut magnam nesciunt, eos excepturi./|/ Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusamus illum quam quod reprehenderit possimus dolor ut magnam nesciunt, eos excepturi./|/ Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusamus illum quam quod reprehenderit possimus dolor ut magnam nesciunt, eos excepturi. "  ]

How can I create a CPT that generates a shortcode and where the user can choose image and text in a custom field. Just like any slider plugin out there? Where the shortcode is displayed on the CPT pages in admin, such as this elementor templates shortcode.

enter image description here

1
  • Have you considered a carousel block containing slide blocks? Do carousels inside reusable blocks not do this? Also there are multiple questions in here, e.g. how to add a column in a post listing, how to register a CPT, how to add an image picker and text in a CPT, each of those should be separate questions. By putting it all together you make your question much harder to answer
    – Tom J Nowell
    Commented Apr 7, 2021 at 11:25

1 Answer 1

0

Add below code on functions.php file and that's it...............

  1. Here, I use slick slider for the carousel view you can change as per your choice.

enter image description here

  1. replace word post with respected post slug in below lines
add_meta_box ( 'customdiv', 'Image Gallery', 'custom_print_box', 'post', 'normal', 'high' );

&&

manage_post_posts_columns

&&

manage_post_posts_custom_column

  1. simply add shortcode in any of the content area which looks like this

enter image description here

  1. below code is totally based on your requirements....
/*
 * Add a meta box
 */
add_action ( 'admin_menu', 'custom_meta_box_add' );
function custom_meta_box_add() {
    add_meta_box ( 'customdiv', 'Image Gallery', 'custom_print_box', 'post', 'normal', 'high' );
}

/*
 * Meta Box HTML
 */
function custom_print_box($post) {
    $meta_key = 'some_custom_gallery';
    echo custom_gallery_field ( $meta_key, get_post_meta ( $post->ID, $meta_key, true ) );
}

/*
 * Save Meta Box data
 */
add_action ( 'save_post', 'custom_save' );
function custom_save($post_id) {
    if( defined ( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return $post_id;

    $meta_key = 'some_custom_gallery';
    update_post_meta ( $post_id, $meta_key, $_POST[ $meta_key ] );
    return $post_id;
}

function custom_gallery_field($name, $value = '') {
    $html   = '<div><ul class="custom_gallery_mtb">';
    $hidden = array ();
    if( $images = get_posts ( array (
        'post_type'      => 'attachment',
        'orderby'        => 'post__in',
        'order'          => 'ASC',
        'post__in'       => explode ( ',', $value ),
        'numberposts'    => -1,
        'post_mime_type' => 'image'
            ) ) ) {

        foreach ( $images as $image ) {
            $hidden[]  = $image->ID;
            $image_src = wp_get_attachment_image_src ( $image->ID, array ( 80, 80 ) );
            $html      .= '<li data-id="' . $image->ID . '"><div><image src="' . $image_src[ 0 ] . '" height="100px" width="100px"/></div><a href="#" class="custom_gallery_remove">Remove Image</a></li>';
        }
    }

    $html .= '</ul><div style="clear:both"></div></div>';
    $html .= '<input type="hidden" name="' . $name . '" value="' . join ( ',', $hidden ) . '" /><a href="#" class="button custom_upload_gallery_button">Add Images</a>';

    return $html;
}

add_action ( 'admin_enqueue_scripts', 'custom_scripts_for_gallery' );

function custom_scripts_for_gallery() {
    wp_enqueue_script ( 'jquery-ui-core' );
    wp_enqueue_script ( 'jquery-ui-widget' );
    wp_enqueue_script ( 'jquery-ui-sortable' );

    if( ! did_action ( 'wp_enqueue_media' ) )
        wp_enqueue_media ();

    wp_enqueue_script ( 'my_scripts', '... /my_scripts.js', array ( 'jquery', 'jquery-ui-sortable' ) );
}

add_action ( 'admin_head', 'my_custom_fonts' ); // admin_head is a hook my_custom_fonts is a function we are adding it to the hook

function my_custom_fonts() {
    ?>
    <style>
        ul.custom_gallery_mtb.ui-sortable {
            display: flex;
        }

        ul.custom_gallery_mtb li {
            margin: 5px;
        }
        .shortcode_wrapper {
            max-width: 100%;
            font-size: 14px!important;
            font-weight: 600;
            display: inline-block;
            background: #fff;
            border: 1px solid #ccd0d4;
            border-width: 10px;
            padding: 1px 12px;
        }
    </style>
    <script>
        function in_array(el, arr) {
            for (var i in arr) {
                if (arr[i] == el)
                    return true;
            }
            return false;
        }
        jQuery(document).ready(function ($) {
            $('ul.custom_gallery_mtb').sortable({
                items: 'li',
                cursor: '-webkit-grabbing', /* mouse cursor */
                scrollSensitivity: 40,
                stop: function (event, ui) {
                    ui.item.removeAttr('style');

                    var sort = new Array(), /* array of image IDs */
                            gallery = $(this); /* ul.custom_gallery_mtb */

                    /* each time after dragging we resort our array */
                    gallery.find('li').each(function (index) {
                        sort.push($(this).attr('data-id'));
                    });
                    /* add the array value to the hidden input field */
                    gallery.parent().next().val(sort.join());
                    /* console.log(sort); */
                }
            });
            /*
             * Multiple images uploader
             */
            $('.custom_upload_gallery_button').click(function (e) {
                e.preventDefault();

                var button = $(this),
                        hiddenfield = button.prev(),
                        hiddenfieldvalue = hiddenfield.val().split(","), /* the array of added image IDs */
                        custom_uploader = wp.media({
                            title: 'Insert images', /* popup title */
                            library: {type: 'image'},
                            button: {text: 'Use these images'}, /* "Insert" button text */
                            multiple: true
                        }).on('select', function () {

                    var attachments = custom_uploader.state().get('selection').map(function (a) {
                        a.toJSON();
                        return a;
                    }),
                            thesamepicture = false,
                            i;

                    /* loop through all the images */
                    for (i = 0; i < attachments.length; ++i) {

                        /* if you don't want the same images to be added multiple time */
                        if (!in_array(attachments[i].id, hiddenfieldvalue)) {

                            /* add HTML element with an image */
                            $('ul.custom_gallery_mtb').append('<li data-id="' + attachments[i].id + '"><div><image src="' + attachments[i].attributes.url + '" height="100px" width="100px"/></div><a href="#" class="custom_gallery_remove">Remove Image</a></li>');
                            /* add an image ID to the array of all images */
                            hiddenfieldvalue.push(attachments[i].id);
                        } else {
                            thesamepicture = true;
                        }
                    }
                    /* refresh sortable */
                    $("ul.custom_gallery_mtb").sortable("refresh");
                    /* add the IDs to the hidden field value */
                    hiddenfield.val(hiddenfieldvalue.join());
                    /* you can print a message for users if you want to let you know about the same images */
                    if (thesamepicture == true)
                        alert('The same images are not allowed.');
                }).open();
            });

            /*
             * Remove certain images
             */
            $('body').on('click', '.custom_gallery_remove', function () {
                var id = $(this).parent().attr('data-id'),
                        gallery = $(this).parent().parent(),
                        hiddenfield = gallery.parent().next(),
                        hiddenfieldvalue = hiddenfield.val().split(","),
                        i = hiddenfieldvalue.indexOf(id);

                $(this).parent().remove();

                /* remove certain array element */
                if (i != -1) {
                    hiddenfieldvalue.splice(i, 1);
                }

                /* add the IDs to the hidden field value */
                hiddenfield.val(hiddenfieldvalue.join());

                /* refresh sortable */
                gallery.sortable("refresh");

                return false;
            });
            /*
             * Selected item
             */
            $('body').on('mousedown', 'ul.custom_gallery_mtb li', function () {
                var el = $(this);
                el.parent().find('li').removeClass('custom-active');
                el.addClass('custom-active');
            });           
        });
    </script>
    <?php
}

add_filter ( 'manage_post_posts_columns', 'smashing_filter_posts_columns' );

function smashing_filter_posts_columns($columns) {
    $columns[ 'shortcode' ] = __ ( 'Shortcode' );
    return $columns;
}

add_action ( 'manage_post_posts_custom_column', 'smashing_realestate_column', 10, 2 );

function smashing_realestate_column($column, $post_id) {
    if( $column == 'shortcode' ) {
        $value = get_post_meta ( $post_id, 'some_custom_gallery' )[ 0 ];
        echo '<div class="shortcode_wrapper">';
        if( ! empty ( $value ) ) {
            echo'[custom-post-gallery post_id="' . $post_id . '"]';
        } else {
            echo'No Images';
        }
        echo '</div>';
    }
}

add_shortcode ( 'custom-post-gallery', 'wpdocs_footag_func' );

function wpdocs_footag_func($atts) {
    $value  = get_post_meta ( $atts[ 'post_id' ], 'some_custom_gallery' );
    $images = get_posts ( array (
        'post_type'      => 'attachment',
        'orderby'        => 'post__in',
        'order'          => 'ASC',
        'post__in'       => explode ( ',', $value[ 0 ] ),
        'numberposts'    => -1,
        'post_mime_type' => 'image'
            ) );
    ?>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script>
    <div class="slider">
        <?php if( ! empty ( $images ) ) { ?>
            <?php
            foreach ( $images as $image ) {
                $image_src = wp_get_attachment_image_src ( $image->ID, array ( 80, 80 ) );
                ?>
                <img width="100px" height="100px" src="<?php echo $image_src[ 0 ]; ?>" />
            <?php } ?>
        <?php } ?>
    </div>
    <script>
        jQuery(document).ready(function ($) {
            $('.slider').slick();
        });
    </script>
    <?php
}

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.