ThemeForest

Adding widget option in functions.php

47 posts
  • Has been a member for 2-3 years
  • Bought between 1 and 9 items
virgild says

I’m trying to develop a widget for the popular posts tutorial here http://bavotasan.com/tutorials/how-to-list-your-most-popular-posts-in-wordpress/

I’m not sure how to replace the $num variable in functions.php with

$options['number'];?> which let’s you pick the number of posts to list. I would think that the best way is to incorporate the entire function into the widget but I’m not sure how.

Can someone please help?

2 years ago
629 posts
  • Has been a member for 2-3 years
  • Repeatedly Helped protect Envato Marketplaces against copyright violations
  • Exclusive Author
  • Bought between 10 and 49 items
  • United States
  • Referred between 10 and 49 users
VagrantRadio says

The first block of code goes into your functions.php file and the second one goes in a text widget. This is how you set the number of posts to show where “10” is the number.

<?php echo popularPosts(10); ?>
2 years ago
47 posts
  • Has been a member for 2-3 years
  • Bought between 1 and 9 items
virgild says

Thanks Vagrant I know that part but how to I set the number of posts via a widget option? $options['number'];?>

2 years ago
629 posts
  • Has been a member for 2-3 years
  • Repeatedly Helped protect Envato Marketplaces against copyright violations
  • Exclusive Author
  • Bought between 10 and 49 items
  • United States
  • Referred between 10 and 49 users
VagrantRadio says
Thanks Vagrant I know that part but how to I set the number of posts via a widget option? $options['number'];?>

Where are you getting this options number code from?

You just put the above php code in the widget and “(10)” is how you set the number of posts.

2 years ago
629 posts
  • Has been a member for 2-3 years
  • Repeatedly Helped protect Envato Marketplaces against copyright violations
  • Exclusive Author
  • Bought between 10 and 49 items
  • United States
  • Referred between 10 and 49 users
VagrantRadio says

in your functions file:

function popularPosts($num) {
    global $wpdb;

    $posts = $wpdb->get_results("SELECT comment_count, ID, post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , $num");

    foreach ($posts as $post) {
        setup_postdata($post);
        $id = $post->ID;
        $title = $post->post_title;
        $count = $post->comment_count;

        if ($count != 0) {
            $popular .= '<li>';
            $popular .= '<a href="' . get_permalink($id) . '" title="' . $title . '">' . $title . '</a> ';
            $popular .= '</li>';
        }
    }
    return $popular;
}

in your text widget:

<?php echo popularPosts(10); ?>  

popularPosts(10) is your number of posts.

2 years ago
287 posts
  • Has been a member for 3-4 years
  • Exclusive Author
  • Sold between 1 000 and 5 000 dollars
  • Bought between 10 and 49 items
  • Referred between 1 and 9 users
by
by
by
by
by