1

I'm looking to display a standard wordpress widget only on posts that are over X amount of characters in length (or another method that can roughly calculate the height of of a post.)

I am looking to include some additional advertising in the sidebar of my sites posts that are very long and thus have empty sidebar space. On shorter posts this is not necessary to display this large additional advert as then otherwise the sidebar would be longer than the main content body and cause issues with layout.

Does anybody know the best solution to achieve this?

I understand it may not be a common thing to ask, but if it's a simple enough solution it could be worth while to implement on the site. Thanks to anyone who can offer some assistance.

4 Answers 4

3

Use the function t5_word_count() from this answer and extend the method widget() in your widget class:

public function widget( $args, $instance )
{
    if ( ! is_singular() )
        return;

    $content = get_the_content( '', TRUE );
    $words   = t5_word_count( $content );

    if ( 50 > $words )
        return;

    // print you widget
}
1

Widget Context allows this as standard. You can select to only how on pages that more than or less than a set number of words!

0

How about doing it with some javascript? I can think of a way:

1) Already add additional widgets to the sidebar, and make them hidden with css

2) On page load use some jquery to calculate the effective height of the post(main content area). This will also take images into account, instead of just words.

3) And comparing the height of main content and sidebar you can set visible those extra widgets

But this approach will have one problem, those widgets, even if they aren't displayed, are loaded on page load, so extra html, etc... To avoid that you can load those widget content with ajax after page load, if extra widgets are to be shown. But that way I am not sure all of the widgets can be fetched through ajax. But for sure, ads can be..

Makes sense?

0

The Widget Logic plugin can filter the content of any widget.

You can hide the widget using the word count from Count the words.

    function hide_widget_if_long_post($content='' , $widget_id='')
    {
       if (t5_word_count(get_the_content()) <= your_limit && $widget_id == "your-widget-id-1" ) {
            return '';
       }
       return $content;
    }

    add_filter('widget_content', 'hide_widget_if_long_post',10,2);

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.