Home > database >  How to use ACF in Wordpress to add multiple images to a custom page template?
How to use ACF in Wordpress to add multiple images to a custom page template?

Time:04-21

I have a number of pages (400) which are all build individually in a visual editor (DIVI), even though they are identical other than the images on each page - This was my first website and so I knew no better than this approach when I began.

They are all child-pages of pageX and their slug begins with a common word. eg:

mysite.com/pageX/commonword-page1/

mysite.com/pageX/commonword-page2/

If I wanted to use a custom page template and insert unique images for each page, how would I go about doing this? Would adding an advanced custom field for each page containing an array of image ids/urls be a good option? Then simply call this and loop through each one and insert into the DOM?

CodePudding user response:

You would download and install ACF from the Plugins directory. Then, create a custom gallery field.

On the page, using the custom field, select the images you want in the gallery. Then in the template, to create a WordPress Gallery use this code:

// Load value (array of ids).
$image_ids = get_field('gallery'); // slug name of the field you created
if( $image_ids ) {

    // Generate string of ids ("123,456,789").
    $images_string = implode( ',', $image_ids );

    // Generate and do shortcode.
    // Note: The following string is split to simply prevent our own website from rendering the gallery shortcode.
    $shortcode = sprintf( '[' . 'gallery ids="%s"]', esc_attr($images_string) );
    echo do_shortcode( $shortcode );
}

This was pulled from the ACF documentation for gallery fields.

Here is their link: https://www.advancedcustomfields.com/resources/gallery/

  • Related