这是在前端显示热门帖子的代码,但问题是数据没有从后端保存。就像我只想在前端显示3个流行帖子,所以我选择了选项3,但它不保存。但是,当我传递的静态值$popularpostcount
那么这个代码就起作用了echo $this->popularPosts($popularpostcount);
因此,我认为问题只在于保存选定的选项。
我是插件开发新手,所以请让我知道在开发过程中我犯了什么错误。
<?php
/*
Plugin Name: Popular Post Widget
Plugin URI: http://demo.test.com
Author: Swapnesh Kumar Sinha
Description: This is a plugin to show popular posts in sidebar as a widget.
Version: 1.0
Author URI: http://swapneshsinha.wordpress.com
*/
class PopularPostWidget extends WP_Widget {
public function __construct() {
//Widget actual processes
$widget_options = array( \'Description\' => \'Show Popular Posts\' );
parent::__construct( \'PopularPostWidget\', \'Popular Post Widget\', $widget_options);
}
public function form( $instance ) {
//outputs the options form on admin
$instance = wp_parse_args( (array) $instance, array( \'popularpostcount\' => \'\' ) );
$popularpostcount = $instance[\'popularpostcount\'];
echo $popularpostcount;
echo "Number of post to show ";
echo "<select name=\'popularpostcount\' id=\'popularpostcount\'>";
for( $i =1; $i<=5; $i++ )
{
if ( $i == $instance[\'popularpostcount\'] )
echo "<option value=\'".$i."\' selected>".$i."</option>";
else
echo "<option value=\'".$i."\'>".$i."</option>";
}
echo "</select>";
}
public function update( $new_instance, $old_instance ) {
//processes widget options to be saved
$instance = $old_instance;
$instance[\'popularpostcount\'] = $new_instance[\'popularpostcount\'];
return $instance;
}
public function widget( $args , $instance ) {
//outputs the content of widget
extract($args);
$popularpostcount = apply_filters(\'widget_title\', $instance[\'popularpostcount\']);
echo "<h2>Most Popular Posts</h2>";
echo "<ul>";
echo $this->popularPosts($popularpostcount);
echo "</ul>";
}
public 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.\'</a> \'." - ".$count;
$popular .= \'</li>\';
}
}
return $popular;
}
}
add_action( \'widgets_init\' , create_function(\'\', \'register_widget( "popularpostwidget" );\' ) );