我正在使用下面的代码创建一个小部件,从下拉列表中选择一篇文章-这在后端运行良好,但我不知道如何在前端显示它。。。
<?php
class RandomPostWidget extends WP_Widget
{
function RandomPostWidget()
{
$widget_ops = array(\'classname\' => \'RandomPostWidget\', \'description\' => \'Displays a featured post\' );
$this->WP_Widget(\'RandomPostWidget\', \'Featured Homepage Post\', $widget_ops);
}
function form($instance)
{
$instance = wp_parse_args( (array) $instance, array( \'title\' => \'\' ) );
$title = $instance[\'title\'];
?>
<p><label for="<?php echo $this->get_field_id(\'title\'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id(\'title\'); ?>" name="<?php echo $this->get_field_name(\'title\'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
<select name="page_id" id="page_id">
<?php
global $post;
$args = array( \'numberposts\' => -1,\'category\' => 5);
$posts = get_posts($args);
foreach( $posts as $post ) : setup_postdata($post); ?>
<option value="<? echo $post->ID; ?>"><?php the_title(); ?></option>
<?php endforeach; ?>
</select>
<?php
}
function update($new_instance, $old_instance)
{
$instance = $old_instance;
$instance[\'title\'] = $new_instance[\'title\'];
return $instance;
}
function widget($args, $instance)
{
extract($args, EXTR_SKIP);
echo $before_widget;
$title = empty($instance[\'title\']) ? \' \' : apply_filters(\'widget_title\', $instance[\'title\']);
if (!empty($title))
echo $before_title . $title . $after_title;;
// WIDGET CODE GOES HERE
echo "<h1></h1>";
echo $after_widget;
}
}
add_action( \'widgets_init\', create_function(\'\', \'return register_widget("RandomPostWidget");\') );
?>
我可能忽略了一些简单的事情,但任何帮助都将不胜感激。
谢谢
最合适的回答,由SO网友:fuxia 整理而成
$instance[\'page_id\']
应为所选帖子的帖子ID。所以…
function widget($args, $instance)
{
$post = get_post( $instance[\'page_id\'] );
echo $post->post_content; // you should add the common filters here
var_dump( $post ); // more data
}
…应该是个好的开始。
要在配置表单中保存最后一个值,请使用selected()
:
foreach( $posts as $post )
{
setup_postdata($post); ?>
<option value="<? echo $post->ID; ?>" <?php
selected( $instance[\'page_id\'], $post->ID );
?>><?php the_title(); ?></option>
<?php
}