2

How to Get a WordPress Widget Outside of the Sidebar

 2 years ago
source link: https://aarontgrogg.com/blog/2021/11/09/how-to-get-a-wordpress-widget-outside-of-the-sidebar/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to Get a WordPress Widget Outside of the Sidebar

  • Share:

I recently needed to insert an existing custom WP Widget’s content into another widget so that I could include it into a page outside of the sidebar.

Meaning, the site has a custom widget that normally lives in the sidebar, but for one specific page, that widget needed to be included somewhere else.

What I expected to find was something like get_widget, which would ideally take the widget’s Title and return the widget’s Content. What I found instead was a bunch of references to the_widget, which “Outputs an arbitrary widget as a template tag”… Well, that could be it…

But it was not; the_widget is useful if you want to create a new widget “on the fly”, so you can pass in the “bits” and it will output those bits within the markup of whatever type of widget you want. Which is not what I want.

So I continued searching and searching and searching, but never found the elusive get_widget that I was sure must exist. Has no other WP developer ever needed a widget outside of the sidebar?

Either no, or it is extremely well hidden…

So here’s what I built…

TL;DR

$title = ;


$widgets = get_option(  );

foreach ( $widgets  $key => $widget ) :

    
     ( mb_strtolower( $widget[] ) !== mb_strtolower( $title ) ) ;

    
     $widget[];

endforeach;
    

The Details

In my theme’s functions.php file, I added the following code (note the numbers in the parentheses correlate to the numbered bullets below the code block, for deeper explanations):

// namespacing my function to reduce the chance of conflicts
if ( ! function_exists( 'atg_get_widget' ) ) :

    // function receives array of attributes passed via the shortcode (1)
    function atg_get_widget( $atts = array() ) {

        // setup placeholder, in case nothing is found (useful for debugging)
        $content = '';

        // merge default parameters with the array the function receives,
        // then extract into named variables (2) (3)
        extract( shortcode_atts( array(
         'title' => ''
        ), $atts) );

        // if the extracted 'title' attribute is empty, 
        // meaning none was provided to the function, 
        // return an HTML comment (useful for debugging)
        if ( $title === '' ) return '';

        // if we have a title, get all Custom HTML widgets (4)
        $widgets = get_option( 'widget_custom_html' );

        // loop through to find the correct widget
        foreach ( $widgets as $key => $widget ) :

            // if this is NOT it, move on (5)
            if ( mb_strtolower( $widget['title'] ) !== mb_strtolower( $title ) ) continue;

            // if this IS it, replace $content placeholder from above
            $content = $widget['content'];
            break;

        endforeach;

        return $content;

    } // atg_get_widget

endif;

// create the shortcode (function name, hook)
add_shortcode('atg_get_widget', 'get_widget');
// call like [atg_get_widget title="My Custom HTML Widget Title"] (6)

Again, the comments pretty much tell the tale, but a few additional notes never hurt…

  1. Call the shortcode with something like:
    [atg_get_widget title="My Custom HTML Widget Title"]
    Any attributes passed into a shortcode get converted into an array and passed to the shortcode’s function.
  2. shortcode_atts is a WordPress function that combines custom & default attributes into a single array, allowing the developer to create defaults attributes that get overwritten by any values passed into the function. In my case, I am creating an empty string default for the title attribute that should be overwritten by whatever gets passed into the shortcode, and thus into the function.
  3. extract is a PHP function that converts a key/value array into named variables and values. In my case, converting something like:
    array( "title" => "Widget Title" )
    into something like:
    $title = "Widget Title" ;
  4. get_option is a WordPress function that returns the requested “option”; the returned data type can vary based on what was requested. In my case, the function returns an array of all Custom HTML Widgets.
  5. While looping through the returned widgets, I compare this loop’s “title” with the one requested by the shortcode. Note that I use mb_strtolower instead of strtolower; mb_strtolower provides support for UTF-8 (international) characters.
  6. It is worth noting that, in order to use shortcodes in a widget, you have to include the following filters in your functions.php file:
    add_filter( 'widget_text', 'shortcode_unautop' );
    add_filter( 'widget_text', 'do_shortcode' );
    

    shortcode_unautop tells WordPress to NOT wrap the shortcode in paragraph tags, and do_shortcode tells the widget to process shortcodes.

Happy widgeting,
Atg

Top⇪

This entry was posted in web development, wp. Bookmark the permalink.

Leave a Reply Cancel reply

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

Comment

Name *

Email *

Website

Save my name, email, and website in this browser for the next time I comment.

Notify me of follow-up comments by email.

Notify me of new posts by email.

 I\'m not a spammer.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Learn More)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK