首页 问答 正文

如何在WordPress中创建自定义小工具?

注册会员 / 悠然自学 / 2023-06-12/ 浏览 133 次

在WordPress中创建自定义小工具非常简单,只需要遵循以下步骤:

  1. 创建一个新的PHP文件,在其中定义一个类。例如,我们可以创建一个名为"My_Custom_Widget"的小工具类:
class My_Custom_Widget extends WP_Widget {

} 
  1. 在类中定义构造函数和小工具逻辑。例如,我们可以在构造函数中定义小工具的名称和描述,并在小工具中显示最近的文章:
class My_Custom_Widget extends WP_Widget {
  public function __construct() {
    parent::__construct(
      'my_custom_widget',
      __('My Custom Widget', 'my_custom_widget_domain'),
      array('description' => __('Displays recent posts', 'my_custom_widget_domain'))
    );
  }

  public function widget($args, $instance) {
    $title = apply_filters('widget_title', $instance['title']);
    $num_posts = apply_filters('widget_num_posts', $instance['num_posts']);

    echo $args['before_widget'];

    if(!empty($title)) {
      echo $args['before_title'] . $title . $args['after_title'];
    }

    $recent_posts = wp_get_recent_posts(array(
      'numberposts' => $num_posts,
      'post_status' => 'publish'
    ));

    echo '<ul>';

    foreach($recent_posts as $post) {
      echo '<li><a href="' . get_permalink($post['ID']) . '">' . $post['post_title'] . '</a></li>';
    }

    echo '</ul>' . $args['after_widget'];
  }
} 
  1. 注册小工具并将其添加到WordPress小工具页面。要注册小部件,请在functions.php或另一个主题文件中添加以下代码:
function my_custom_widget_load() {
  register_widget('My_Custom_Widget');
}

add_action('widgets_init', 'my_custom_widget_load'); 

这将使自定义小工具出现在WordPress小工具页面中。

示例代码:https://gist.github.com/skippednote/3055cfab45f65abc90395e4dfbe98368

大家谈论
    我的见解