0

I'm implementing a custom widget to create a logos slider. The initial code works well, but when I have added a metabox to the attachment screen to let the user add an external link to the images, I get some problems. What I want to do is to add the metabox, save it's value and when the widget is loaded on the front-end, retrive back the link that user have added for each image. The images are not attached to any post, and for now I'm able to see the new metabox but it can be edited only if the user click on the edit link of each image in the media library, I would prefere to see the box on the main selection screen of media gallery. I'm also unable to get the field value, I think because inside the code the images ids are not loaded.

public function initMetabox()
  {
    add_meta_box(
      'image_link_box',
      __('Link image to url'),
      array($this, 'renderMetabox'),
      'attachment'
    );
  }

  public function renderMetabox( $post )
  {
    $url = get_post_meta( $post->ID, '_image_link_url', true );
    ?>
    <label for="image-link"><?php _e('Image Link'); ?></label>
    <input type="text" name="image_link" id="image-link" value="<?php echo $url; ?>" class="postbox">
    <?php
  }

  public function saveLink( $post_id )
  {
    if( in_array( 'image_link', $_POST ) ){
      update_post_meta(
        $post_id,
        '_image_link_url',
        $_POST['image_link']
      );
    }
  }

  public function widget( $args, $instance )
  {
    $images = explode( ',', $instance['images'] );
    $image_link = get_post_meta( $post->ID, '_image_link_url', true );

    ob_start();
    ?>
    <div class="swiper-container logo-slider" id="featured-logo-slider">
      <div class="swiper-wrapper" id="featured-logo">
        <?php foreach( $images as $image ): ?>
          <?php foreach( $image_link as $link ): ?>
            <a href="<?php echo $link; ?>"><img class="swiper-slide" src="<?php echo $image; ?>" alt="" width="100" id="client-logo"/></a>
          <?php endforeach; ?>
        <?php endforeach; ?>
      </div>
      <div class="swiper-scrollbar"></div>
    </div>
    <?php
    echo ob_get_clean();
  }

The foreach loop for the images links will produce an error Invalid argument supplied... and the $post->ID variable is not available. Any suggestion will be appreciated

1 Answer 1

0

It looks that a reference to global $post; is missing at the beginning of your function widget(){}

1
  • In the original code I've wrapped inside the class, I was using am image gallery and some wp functions to get the attached images ids. Here I'm not sure if this works if I only add the reference to the global $post variable. I need to try
    – sialfa
    Commented Jan 13, 2020 at 11:56

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.