WordPress小部件:显示单个帖子

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WordPress小部件:显示单个帖子相关的知识,希望对你有一定的参考价值。

A simple widget for displaying a single post in a dynamic sidebar. Originally developed to accommodate a WP user who wanted full control of which posts were displayed and what order they were on a certain page.
  1. <?php
  2. /*
  3. Plugin Name: Single Post
  4. Plugin URI: http://ch4ze.com
  5. Description: Define a widget for displaying a single post
  6. Author: Chase Crawford
  7. Author URI: http://ch4ze.com
  8. Version: 0.1
  9. */
  10.  
  11.  
  12. class singlePostWidget extends WP_Widget
  13. {
  14. function singlePostWidget()
  15. {
  16. $widget_ops = array('classname' => 'singlePostWidget', 'description' => 'Displays a single post' );
  17. $this->WP_Widget('singlePostWidget', 'Single Post', $widget_ops);
  18. }
  19.  
  20. function form($instance)
  21. {
  22. $instance = wp_parse_args( (array) $instance, array( 'pid' => '' ) );
  23. $pid = $instance['pid'];
  24. if($pid == '') {
  25.  
  26. $args = array(
  27. 'post_type' => 'post'
  28. );
  29. $the_query = new WP_Query($args);
  30. print '<select name="' . $this->get_field_name('pid') . '"><option value ="">Choose a post to display</option>';
  31. while ( $the_query->have_posts() ) :
  32. $the_query->the_post();
  33.  
  34. print '<option value="' . get_the_ID() . '">' . get_the_title() . '</option>';
  35.  
  36. endwhile;
  37. print '</select>';
  38.  
  39. } else {
  40.  
  41. $post = query_posts('p=' . $pid);
  42. while ( have_posts() ) : the_post();
  43.  
  44. print "<strong>" . get_the_title() . "</strong>";
  45.  
  46. endwhile;
  47.  
  48. }
  49.  
  50. }
  51.  
  52. function update($new_instance, $old_instance)
  53. {
  54. $instance = $old_instance;
  55. $instance['pid'] = $new_instance['pid'];
  56. return $instance;
  57. }
  58.  
  59. function widget($args, $instance)
  60. {
  61. extract($args, EXTR_SKIP);
  62.  
  63. $post = query_posts('p=' . $instance['pid']);
  64. while ( have_posts() ) : the_post();
  65.  
  66. /*=======================================================
  67.   add template code to display your post here
  68.   =======================================================*/
  69.  
  70. endwhile;
  71.  
  72.  
  73. }
  74.  
  75. }
  76. add_action( 'widgets_init', create_function('', 'return register_widget("singlePostWidget");') );?>

以上是关于WordPress小部件:显示单个帖子的主要内容,如果未能解决你的问题,请参考以下文章

如何在 WordPress 中显示自定义的最近帖子?

php EMPTY WIDGET用于在wordpress中创建单个小部件的插件代码。

从WordPress小部件获取数据以修改帖子内容

Wordpress:最近的帖子小部件

Wordpress 自定义演示侧边栏未出现在帖子上

PHP 将帖子计数移动到WordPress的存档和类别小部件的链接中