1

I'm creating a custom widget and I want to return a different element ID. The ID would be something like, instafeed-sidebar and instafeed-footer. This is depending where the widget added.

Register sidebars:

register_sidebar( array(
    'name'          => esc_html__( 'Post Sidebar', 'nubia' ),
    'id'            => 'post-sidebar',
    'description'   => esc_html__( '', 'nubia' ),
    'before_widget' => '<section id="%1$s" class="c-widget c-widget--sidebar %2$s">',
    'after_widget'  => '</section>',
    'before_title'  => '<h5 class="c-widget--sidebar__title">',
    'after_title'   => '</h5>',
  ) );

  register_sidebar( array(
    'name'          => esc_html__( 'Footer First', 'nubia' ),
    'id'            => 'footer-first',
    'description'   => esc_html__( '', 'nubia' ),
    'before_widget' => '<section id="%1$s" class="c-widget c-widget--footer %2$s">',
    'after_widget'  => '</section>',
    'before_title'  => '<h5 class="c-widget--footer__title">',
    'after_title'   => '</h5>',
  ) );

Widget code:

public function widget( $args, $instance ) {
  extract($args);

  // ...

  <div id='instafeed' class='c-widget-instagram'></div>

  <?php

  echo $after_widget;
}

I don't want to use the widget dynamic ID, but rather an ID that I choose.

So if the widget added to the registered sidebar, the element would be:

<div id='instafeed-sidebar' class='c-widget-instagram'></div>

If the widget added to the footer, the element would be:

<div id='instafeed-footer' class='c-widget-instagram'></div>

Thanks,

  • in the method widget you can read the sidebar identifier in $args["id"]. – mmm Apr 8 '18 at 21:25
2

Solved it by following the advice from @mmm. Using $args["id"] did the trick.

Using $args["id"] will return the following:

post-sidebar

footer-first

With a little change, my final code is:

public function widget( $args, $instance ) {
  extract($args);

  // ...

  <div id='instafeed-<?php echo explode("-", $args["id"])[0] ;?>' class='c-widget-instagram'></div>

  <?php

  echo $after_widget;
}

The result is:

<div id='instafeed-post' class='c-widget-instagram'></div>
<div id='instafeed-footer' class='c-widget-instagram'></div>

Thanks

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.