Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wordpress count widgets

Hi I am trying to figure out as to how can we get the count of widgets published in a given sidebar position.

For example I have a sidebar called UTILITY which is a horizontal sidebar. I want the width of these widget positions to adjust equally according to the number of widgets published in it.

I want to know that on a given page how many widgets are published in this sidebar so that I can assign a width class according to it.

like image 203
Vikram Rao Avatar asked Dec 14 '10 16:12

Vikram Rao


People also ask

What is a counter widget?

The Counter Widget enables you to add an animated numbered counter to your page.

Does WordPress have a visitor counter?

PRO TIP: WordPress does not have a visitor counter. If you are looking for a way to track your website's traffic, we recommend using a third-party service such as Google Analytics. The counter will show you the number of visits your site has received, as well as the number of unique visitors.


1 Answers

wp_get_sidebars_widgets()

Will give you an array of the sidebars and the widgets they have, just count the array for the appropriate sidebar..

For example:

$the_sidebars = wp_get_sidebars_widgets();
echo count( $the_sidebars['my-sidebar-id'] );

The ID is the one you declare when you register the sidebar(so check your sidebar registration code).

You could also wrap this into a function.

function count_sidebar_widgets( $sidebar_id, $echo = true ) {
    $the_sidebars = wp_get_sidebars_widgets();
    if( !isset( $the_sidebars[$sidebar_id] ) )
        return __( 'Invalid sidebar ID' );
    if( $echo )
        echo count( $the_sidebars[$sidebar_id] );
    else
        return count( $the_sidebars[$sidebar_id] );
}

Then call it when you need to get the count, using the sidebar ID..

count_sidebar_widgets( 'some-sidebar-id' );

Or store in variable for other usage..

$my_var = count_sidebar_widgets( 'some-sidebar-id', false );

Hope that helps..

like image 130
t31os Avatar answered Oct 11 '22 22:10

t31os