Add an ACF field into WordPress admin posts list

Web development | 0 comments

Introduction

To create an easy-to-administer photo gallery for a client, I used the ACF WordPress plugin to create a custom post type that I called “gallery”. I configured it to keep the “title” and “category” fields and remove the content and tags. Still with ACF I then added an image type field called “photo” allowing to upload photos or add them from the media library which was configured to return the image array.

Add a photo page

To make it easier for him to manage this gallery, I wanted to display a preview of the photos in the list of posts in his administration panel. To do this, I integrated the following code into an extension created for his website but it is also possible to insert it into the functions.php file of your theme.

List of photos in admin panel

Code

<?php
/**
 * Add a column names photo_thumbnail to the table
 */
function add_thumbnail_columns($columns) {
    $new_columns = array();
    foreach($columns as $key => $value) {
        if ($key == 'title') { // Put the Thumbnail column before the title column
            $new_columns['photo_thumbnail'] = __('Thumbnail');
        }
        $new_columns[$key] = $value;
    }
    return $new_columns;
}
add_filter('manage_edit-gallery_columns', 'add_thumbnail_columns');

/**
 * Output ACF photo in the photo_thumbnail column
 */
function thumbnail_columns_content($column, $post_id) {
    if ($column == 'photo_thumbnail') {
	$post = get_post($post_id);
	setup_postdata($post);
	$image = get_field('photo');
	echo '<a href="'.get_edit_post_link().'"><img src="'.$image['sizes']['thumbnail'].'" /></a>';
	wp_reset_postdata();
    }
}
add_filter('manage_gallery_posts_custom_column' , 'thumbnail_columns_content', 10 , 2);

Explainations

The add_thumbnail_columns() function allows you to insert the column called “photo_thumbnail” with the label “Thumbnail” between the check box and the title.

The thumbnail_columns_content() function allows you to insert the photo in the line with the link to the editor.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *