0

I have the following code in a self-written plugin. In the function saveHomepageGalleryCheckbox the first param ($post) is always null. Did I something wrong? The second parameter ($attachment) has the correct value.

  • Wordpress Version: 5.3.2
  • PHP Version: 7.3.15

Code:

class MediaView
{
  private $key = 'include_in_homepage_gallery';

  public function __construct()
  {
    add_filter('attachment_fields_to_edit', [$this, 'renderHomepageGalleryCheckbox'], 10, 2);
    add_filter('attachment_fields_to_save', [$this, 'saveHomepageGalleryCheckbox'], 10, 2);
  }

  public function renderHomepageGalleryCheckbox(array $fields, WP_Post $post)
  {
    $meta = get_post_meta($post->ID, $this->key, true);
    $checked = (boolval($meta) === true) ? 'checked="checked"' : '';
    $id = "attachments[{$post->ID}][{$this->key}]";

    $fields[$this->key] = [
      'label' => 'Homepage Gallery',
      'input' => 'html',
      'html' => "<input type=\"checkbox\" name=\"$id\" id=\"$id\" value=\"1\" {$checked} />"
    ];

    return $fields;
  }

  public function saveHomepageGalleryCheckbox($post, array $attachment) // Here is $post === null
  {
    if (isset($attachment[$this->key])) update_post_meta($post['ID'], $this->key, 1);
    else update_post_meta($post['ID'], $this->key, 0);

    return $post;
  }
}
  • I notice in your saveHomepageGalleryCheckbox filter you never return anything, is there a reason for that? Filters always return something. Alos why do you have null as the priority? Do you have any other filters operating on attachment_fields_to_save? – Tom J Nowell Mar 12 at 11:56
  • I updated my code, but it doesn´t change anything about the $post param. – sydev Mar 12 at 13:01
  • True, but they were still issues. Think of it as a kitchen oven repairman telling you the fridge has died, it's not going to fix the oven, but it's still a problem that needs fixing, that's why I left a comment instead of an answer, I'm not sure why your $post is null. Note that if another filter has made the same mistake, then this would explain why $post is null, as the next filter called would recieve a null if the filter did not return anything – Tom J Nowell Mar 12 at 13:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.