set and unset the custom field value

I realize this is almost 2 years too late, but I hope it’s still useful to some people that land here looking for an answer.

Disclaimer: this is not a great pattern according to WordPress admin design patterns, but it’s actually nice to use in a pinch.

Insert the following into your functions.php file in your theme

Set your admin column heading

function set_column_heading( $defaults ) {
    $defaults['featured_image'] = 'Featured Image';
    return $defaults;
}
add_filter( 'manage_posts_columns', 'set_column_heading' );

Set your admin column value

This has changed to handle the current status of whether or not the featured image is set to be displayed by fetching post meta. It also handles the nonce.

function set_column_value( $column_name, $post_ID ) {
    if ( 'featured_image' === $column_name ) {
        $post_featured_image = get_featured_image( $post_ID );
        if ( $post_featured_image ) {
            $featured_image_display = get_post_meta( $post_ID, 'show_featured_image' );
            $show_class="show";
            $show_text="Display Featured Image";
            if ( $featured_image_display ) {
                $show_class="hide";
                $show_text="Hide Featured Image";
            }
            echo '<button class="' . esc_attr( $show_class ) . '" data-nonce="' . esc_attr( wp_create_nonce( 'my_display_featured_image_' . $post_ID ) ) . '">' . esc_html( $show_text ) . '</button>';
        }
    }
}

function get_featured_image( $post_ID ) {
    $post_thumbnail_id = get_post_thumbnail_id( $post_ID );
    if ( $post_thumbnail_id ) {
        $post_thumbnail_img = wp_get_attachment_image_src( $post_thumbnail_id, 'featured_preview' );
        return $post_thumbnail_img[0];
    }
}
add_action( 'manage_posts_custom_column', 'set_column_value', 10, 2 );

Enqueue your script on the post list page.

This is pretty simple. Make sure your script path is correct and jQuery is a dependency.

add_action( 'admin_enqueue_scripts', 'my_enqueue_admin_scripts' );
function my_enqueue_admin_scripts( $hook ) {
    if ( 'edit.php' !== $hook ) {
        return;
    }
    wp_enqueue_script( 'set_featured_image', get_template_directory_uri() . '/js/set-featured-image.js', array( 'jquery' ), '1.0.0', true );
}

Register an admin-only ajax response function

This response to the ajax request we have in our javascript, set-featured-image.js. This updates the post meta to reflect the status. It also handles the nonce verification.

add_action( 'wp_ajax_my_display_featured_image', 'my_display_featured_image' );
function my_display_featured_image() {
    if ( ! isset( $_POST['featuredImage'], $_POST['postID'] ) ) {
        wp_send_json_error( array( 'isset' ) );
        wp_die();
    }
    if ( ! is_numeric( $_POST['postID'] ) ) {
        wp_send_json_error( array( 'checks' ) );
        wp_die();
    }

    $post_id = intval( $_POST['postID'] );
    check_ajax_referer( 'my_display_featured_image_' . $post_id );

    $set_featured_image = wp_validate_boolean( $_POST['featuredImage'] );

    update_post_meta( $post_id, 'show_featured_image', $set_featured_image );

    wp_send_json( array( 'featuredImage' => $set_featured_image ) );
    wp_die();
}

Insert the following into the new script you’re enqueuing, set-featured-image.js

Handle the click event and ajax request

When you click the button the correct data is put together, handles the UI changes, and sends the data to our ajax response handler in PHP, my_display_featured_image(). Once we get a response, it updates the button status to reflect the correct value we stored in post meta.

(function($) {
  $('.featured_image button').on('click', function(e) {
    e.preventDefault();
    var $button = $(this);
    var display = false;
    if($button.hasClass('show')) {
      display = true;
    }
    var postID = $button.parents('tr').attr('id').replace(/post-/g, '');
    $button.attr('disabled', true);
    var data = {
      action: 'my_display_featured_image',
      featuredImage: display,
      postID: postID,
      _wpnonce: $button.data('nonce')
    };

    $.ajax({
      type: "POST",
      url: ajaxurl,
      data: data,
      success: function(response) {
        $button.removeAttr('disabled');
        console.log(response);
        if (response.featuredImage) {
          $button.text('Hide Featured Image');
          $button.attr('class', 'hide');
        } else {
          $button.text('Display Featured Image');
          $button.attr('class', 'show');
        }
      }
    });
  });
})(jQuery);

The result

The admin column appears with buttons for each post that has a featured image. The button text reflects whether or not the post meta is set to display the featured image. When you click on the button it toggles the status of this post meta value.

In your templates, all you have to do is get this post meta and use it to conditionally display the featured image.

$featured_image_display = get_post_meta( get_the_ID(), 'show_featured_image' );
if ( $featured_image_display ) { 
    // Display featured image.
}

Leave a Comment