欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

wordpress 自定义_定义自己的WordPress小部件

程序员文章站 2022-04-17 16:33:31
...

wordpress 自定义

Widgets are small pieces of content that can be placed in one of the widgetized regions of your WordPress theme. A widget may contain some simple static content like a newsletter subscription form, introductory text, advertisements or some dynamic content such as a list of recent tweets from your Twitter account.

小部件是一小部分内容,可以放在WordPress主题的小部件区域之一中。 小部件可能包含一些简单的静态内容,例如时事通讯订阅表单,介绍性文本,广告或一些动态内容,例如来自您的Twitter帐户的最新推文列表。

In this article you will learn:

在本文中,您将学习:

  1. How to create simple widgets without coding using the Text widget.

    如何创建简单的小部件而不使用“文本”小部件进行编码。
  2. How to create dynamic data-driven widgets created through a WordPress plugin.

    如何创建通过WordPress插件创建的动态数据驱动的小部件。

静态小部件 (Static Widgets )

Static widgets can be used to place some unchanging text or HTML code in a region. These are very easy to create and they will be sufficient for most content you will need to add to your blog’s sidebars.

静态小部件可用于在区域中放置一些不变的文本或HTML代码。 这些非常易于创建,足以满足您需要添加到博客侧边栏中的大多数内容。

创建静态小部件 (Creating Static Widgets)

In this example we will create a widget that will show a subscription form to an email newsletter in the sidebar of the blog. Follow the steps below having logged into the WordPress administration panel.

在此示例中,我们将创建一个小部件,该小部件将在博客的边栏中显示电子邮件通讯的订阅表单。 按照以下步骤登录到WordPress管理面板。

wordpress 自定义_定义自己的WordPress小部件

Drag and drop the Text widget to a region in the sidebar as shown in the image below:

将“文本”小部件拖放到侧栏中的某个区域,如下图所示:

wordpress 自定义_定义自己的WordPress小部件

Expand the menu and paste the needed text or HTML code:

展开菜单并粘贴所需的文本或HTML代码:

wordpress 自定义_定义自己的WordPress小部件

Click on the Save button. The widget with its content will appear in the front end of the website in the sidebar as shown in the image below:

单击保存按钮。 包含其内容的窗口小部件将显示在网站的侧边栏中,如下图所示:

动态小部件 (Dynamic Widgets)

In this tutorial we will create a widget for showing a Twitter feed in the sidebar. I will illustrate this example by creating a plugin that adds a new Widget called “Twitter Feed” to the Widgets interface. To accomplish the same with the theme, place the entire code in the functions.php file of your WordPress theme.

在本教程中,我们将创建一个小部件,以在侧栏中显示Twitter feed。 我将通过创建一个插件来说明该示例,该插件向Widgets界面添加了一个名为“ Twitter Feed”的新Widget。 要实现与主题相同的functions.php ,请将整个代码放在WordPress主题的functions.php文件中。

创建一个WordPress插件 (Creating A WordPress Plugin)

Before starting the definition of the Widget we must first create the plugin that will contain the definition.

在开始定义小部件之前,我们必须首先创建将包含该定义的插件。

步骤1.创建插件文件 (Step 1. Create Plugin File)

Create a file named tweet_feed.php in the wp-content/plugins/ directory under your WordPress installation directory.

在WordPress安装目录下的wp-content/plugins/目录中创建一个名为tweet_feed.php的文件。

步骤2:添加插件声明注释 (Step 2: Add The Plugin Declaration Comments)

<?php

/*
Plugin Name: Twitter Feed Widget
Author: Raj Sekharan
Author URI: http://www.nodesman.com
Description: Add a twitter feed to your sidebar.
*/

Open a PHP code section and then place the comment section. WordPress looks for the above comments in the first few line of a PHP file to identify it as a wordpress plugin file. The information in this comment section will be used to show the plugin in the plugins administration page.

打开一个PHP代码部分,然后放置注释部分。 WordPress在PHP文件的前几行中查找以上注释,以将其标识为wordpress插件文件。 此注释部分中的信息将用于在插件管理页面中显示插件。

步骤3:创建WP_Widget的子类 (Step 3: Create A Sub Class Of WP_Widget)

Create a sub class of the predefined class WP_Widget with a descriptive name. I will use Twitter_Feed_Widget in this case. The sub class should have four methods:

创建具有描述性名称的预定义类WP_Widget的子类。 在这种情况下,我将使用Twitter_Feed_Widget 。 子类应具有四个方法:

  1. widget()

    widget()

  2. update()

    update()

  3. form()

    form()

  4. Twitter_Feed_Widget()   (or whatever the name of your widget class is)

    Twitter_Feed_Widget() (或任何小部件类的名称)

Even if your server is running PHP5 it is necessary to define a function with the same name as the class name.

即使您的服务器运行的是PHP5,也必须使用与类名相同的名称定义一个函数。

class Twitter_Feed_Widget extends WP_Widget
{
    function  widget($args,$instance)
    {       

    }

   function Twitter_Feed_Widget()
   {

   }

   function  update($new_instance,$old_instance)
   {

   }

   function form($instance)
   {

   }
}

This forms the framework in which the entire definition of the widget will be placed. In the above set of functions only the Twitter_Feed_Widget() and widget() functions are mandatory.

这形成了将放置小部件的整个定义的框架。 在上述函数集中,只有Twitter_Feed_Widget()widget()函数是必需的。

The Widget Options Panel is Optional

窗口小部件选项面板是可选的

wordpress 自定义_定义自己的WordPress小部件

Defining the form() and update() functions is optional. They are necessary only if your widget needs some configuration input from the user. You can leave them out if you don’t want to provide any widget options. In that case the options panel will shown as given in the image below.

定义form()update()函数是可选的。 仅当您的窗口小部件需要用户输入一些配置时,它们才是必需的。 如果您不想提供任何小部件选项,则可以将其忽略。 在这种情况下,选项面板将如下图所示。

步骤4:定义选项面板界面 (Step 4:  Define the Options Panel Interface)

WordPress expects the form() function defined above to output the input fields to the receive input from the user. In the case of the Twitter Feed widget we will provide the following options:

WordPress希望上面定义的form()函数将输入字段输出到用户的接收输入中。 对于Twitter Feed小部件,我们将提供以下选项:

  1. Title of the Widget

    小部件的标题
  2. Username of Twitter user

    Twitter用户的用户名
  3. Number of tweets to show.

    要显示的推文数量。

Below is the definition of the form() function for the Twitter feed widget:

以下是Twitter feed小部件的form()函数的定义:

function form($config)
{
?>
    <label for="<?php echo $this->get_field_id("title");  ?>">
    <p>Title: <input type="text"  value="<?php echo $config['title']; ?>" name="<?php  echo $this->get_field_name("title"); ?>" id="<?php  echo $this->get_field_id("title") ?>"></p>
    </label>

    <label for="<?php echo $this->get_field_id("username");  ?>">
    <p>Twitter Username: <input  type="text" value="<?php echo $config['username'];  ?>" name="<?php echo  $this->get_field_name("username"); ?>" id="<?php  echo $this->get_field_id("username") ?>"></p>
    </label>

    <label for="<?php echo  $this->get_field_id("num"); ?>">
    <p>Number Of Tweets: <input  type="text" size="3" value="<?php echo  $config['num']; ?>" name="<?php echo  $this->get_field_name("num"); ?>" id="<?php echo  $this->get_field_id("num") ?>"></p>
    </label>
<?php        
}

The form() Function Explained

form()函数解释

  1. The function takes one argument – $config. This variable contains the configuration values for this widget.

    该函数接受一个参数– $config 。 此变量包含此窗口小部件的配置值。

  2. The fields in the options are placed within a <form> tag that is submitted via an AJAX request. Which means a form tag shouldn’t be added in the definition above. WordPress handles the saving of the widget data for you.

    选项中的字段放置在通过AJAX请求提交的<form>标记内。 这意味着不应在上面的定义中添加表单标签。 WordPress为您处理小部件数据的保存。

  3. The $this->get_field_name() and $this->get_field_id() functions are used to generate names for the form fields so that there are no conflicts in names with the input fields on the Widget options page.

    $this->get_field_name()$this->get_field_id()函数用于为表单字段生成名称,以使名称与“ $this->get_field_id()小部件选项”页面上的输入字段没有冲突。

步骤5:保存选项面板设置 (Step 5: Save Options Panel Settings)

The business logic that saves the settings selected in the options panel above should be placed in the save() function. In the case of our Twitter feed:

保存上面选项面板中选择的设置的业务逻辑应放在save()函数中。 对于我们的Twitter feed:

function update($newinstance,$oldinstance)
{
    $instance =  $oldinstance;
    //update the username
    $instance['username']=  $newinstance['username'];
    $instance['title'] =  $newinstance['title'];
    $num = (int)$newinstance['num'];
    $num = intval($num);
    $num = ($num>1)?$num:1;
    $instance['url'] = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name={$newinstance['username']}&count={$num}";
    $instance['num'] = $num;
    return $instance;
}

The update() Function Explained

update()函数解释

  • The function takes two arguments :

    该函数有两个参数:
  1. The first argument – $newinstances in this case – has the configuration information of the widget as it was entered in the options panel. WordPress automatically detects all the form elements and uses their names for array elements.

    第一个参数-在这种情况下$newinstances具有在选项面板中输入时小部件的配置信息。 WordPress自动检测所有表单元素并将其名称用于数组元素。

  2. The second argument – $oldinstance in this case – has the configuration information of the Widget prior to changing the settings.

    第二个参数–在这种情况下$oldinstance –在更改设置之前具有Widget的配置信息。

  • Line 4 of the function updates the title of the widget.

    函数的第4行更新了小部件的标题。
  • Line 8 of the function updates the URL of the Twitter API user timline JSON feed.

    该函数的第8行更新了Twitter API用户timline JSON feed的URL。
  • Lines 9 saves the number of tweets to show ensuring that the value is an integer and positive.

    第9行保存了tweet的数量,以确保该值是整数且为正数。
  • Options Panel Doesn’t Support File Uploads

    选项面板不支持文件上传

    You cannot add a file field in the options panel of a widget. If your configurable widget takes file inputs from the user then you must create a separate administration screen for the widget’s options and add a URL field in the widget configuration form.

    您不能在窗口小部件的选项面板中添加文件字段。 如果您的可配置窗口小部件从用户那里获取文件输入,那么您必须为窗口小部件的选项创建一个单独的管理屏幕,并在窗口小部件配置表单中添加URL字段。

    步骤6:定义小部件 (Step 6: Define the Widget )

    Now we are going to define the widget itself. WordPress expects the HTML of the widget to be generated by a function named widget(). Shown below is the definition of the Twitter Widget:

    现在,我们将定义小部件本身。 WordPress希望小部件HTML由名为widget()的函数生成。 下面显示的是Twitter窗口小部件的定义:

    function widget($args,$instance)
    {
         extract($args,EXTR_SKIP);
         if (empty($instance['url']) || empty($instance['username']))
        	  return;
         $title =  ($instance['title'])?$instance['title']:"Latest Tweets";
    
         $tweets =  $this->get_tweets($instance['url'],$instance['username'],$instance['num']);
         $max = $instance['num'];
         echo $before_widget;
    ?>
    <div class="twitter-feed-widget">
    <php echo $before_title; ?>
    <strong><?php echo $title; ?></strong>
    <php echo $after_title; ?>
    <?php
    $count=0;
    foreach ($tweets as $tweet)
    {
        $text = $tweet['tweet'];
    ?>
    <div class="tfw-tweet"><a href="<?php echo $tweet['url'] ?>"><?php echo $text;  ?></a></div><br/>
    <?php
        $count++;
        if ($count == $num)
         break;
    }
    ?>
    </div>
    <?php
    echo $after_widget;
    }
    

    The widget() Function Explained

    widget()函数解释

    The widget function takes two parameters: $args and $instance.

    小部件函数有两个参数: $args$instance

    1. The $args variable contains a few theme relaetd variables:

      $ args变量包含一些主题相关的变量:
    1. before_widget – The HTML to be printed before the widget body.

      before_widget –在小部件主体之前要打印HTML。

    2. >after_widget – The HTML to be printed after the widget body.

      > after_widget –在小部件主体之后要打印HTML。
    3. before_title – The HTML to be printed before the title of the widget.

      before_title –要在小部件标题之前打印HTML。

    4. after_title – The HTML to be printed after the title fo the widget.

      after_title –在小部件标题之后打印HTML。

    • The above mentioned variables are set in the WordPress theme by the Theme author in the declaration of the theme sidebar in the functions.php file.

      上述变量由主题作者在WordPress主题中在functions.php文件中主题侧栏的声明中设置。

    • The variable $instance has the configuration information for this widget instance that was saved in the update() function in the previous step.

      变量$instance具有此小部件实例的配置信息,该信息已在上一步中保存在update()函数中。

    • The get_tweets() function above will fetch tweets of the twitter user passed in the variable $username. The tweets are returned as an associative array. The implementation of the function is as below:

      上面的get_tweets()函数将获取在$username变量中传递的twitter用户的tweets。 这些推文将作为关联数组返回。 该功能的实现如下:

        function get_tweets($feed_url,$username, $num=10)
         {
             //check if the feed is in the list of feeds
             $feeds = get_option("_tfw_feeds");
             $hash = md5($feed_url);
             $tweets = array();
             if (isset($feeds[$hash]))
             {
                 $timeOfLastFetch = intval(@$feeds[$hash]["last_update"]);
                 if ($timeOfLastFetch-time() >300) //update the tweets every 5 minutes
                 {
                      $whetherUpdateTweets = true;
                 }
                 else
                 {
                       if (is_array($feeds[$hash]['tweets']) && count($feeds[$hash]['tweets'] >= $num))
                       {
                          return $feeds[$hash]['tweets'];
                       }
                       else
                       {
                            $whetherUpdateTweets=true;
                       }
                 }
             }
             else
                 $whetherUpdateTweets = true;      
      
             if ($whetherUpdateTweets)
             {
      	       if ($tweetsList = file_get_contents($feed_url))
      	       {
      		   $tweetsList = json_decode($tweetsList);
      		   foreach ($tweetsList as $tweet)
      		   {
      		       $tweets[] = array("tweet"=>$tweet->text,"url"=>"https://twitter.com/#!/{$username}/status/{$tweet->id_str}");
      		   }
      	       }
      	       $hash = md5($feed_url);
      	       $feeds = get_option("_tfw_feeds");
      	       $feeds[$hash] = array("last_update"=>time(),"tweets"=>$tweets);
      	       update_option("_tfw_feeds",$feeds);
             }
             return $tweets;
      
         }
      
    • The first line of the calls the extract() function. The function takes an associative array. It creates variables named after the keys of the array and sets them to the value corresponding to those keys.

      调用的第一行调用extract()函数。 该函数采用一个关联数组。 它创建以数组的键命名的变量,并将其设置为与这些键对应的值。

    • The second line ensures that the widget is not shown at all if the user doesn’t save their username.

      第二行确保如果用户不保存其用户名,则完全不显示该小部件。
    • The fourth line ensures that the $title variable is always set to a usable string.

      第四行确保$title变量始终设置为可用字符串。

    • The next four lines print the content of the above mentioned theme related variables.

      接下来的四行显示上述主题相关变量的内容。
    • The get_tweets() function retrieves a list of tweets of the twitter user. The RSS filename that was saved in the update step is passed to this function as a parameter. It returns an array of associative arrays each of which have the tweet text and the URL to the tweet as elements.

      get_tweets()函数检索twitter用户的tweet列表。 在更新步骤中保存的RSS文件名将作为参数传递给此函数。 它返回一个关联数组的数组,每个关联数组都具有tweet文本和tweet的URL作为元素。

    • The foreach loop prints the tweets.

      foreach循环将打印鸣叫。

    步骤7:定义窗口小部件类构造函数 (Step 7: Define The Widget Class Constructor)

    The widget class’s constructor gives WordPress some information on the widget. The name of the widget, the dimensions of the widget’s options panel, the description to be shown under the widget’s name in the Widgets administration page are all configured in this function. This constructor defines two arrays and then passes them to the WP_Widget parent class.

    小部件类的构造函数为WordPress提供了有关小部件的一些信息。 窗口小部件的名称,窗口小部件的选项面板的尺寸,将在窗口小部件管理页面中的窗口小部件名称下显示的描述均已在此功能中配置。 此构造函数定义了两个数组,然后将它们传递给WP_Widget父类。

    function Twitter_Feed_Widget()
    {
       $widget_options = array(
          'classname'=>'widget-tweet',
          'description'=>__('This widget shows the twitter feed for the selected user.')
       );
       $control_options = array(
          'height'=>300,
          'width' =>300
       );
       $this->WP_Widget('twitter_feed_widget','Twitter Feed Widget',$widget_options,$control_options);
    }
    

    The Constructor Explained

    构造函数解释

    1. The first argument to the parent class constructor is a unique identified for the widget defined by this class. The widget’s content will be enclosed in a <div> element. This element’s class attribute will be set to this value.

      父类构造函数的第一个参数是为此类定义的窗口小部件唯一的标识。 小部件的内容将包含在<div>元素中。 该元素的class属性将设置为此值。

    2. The second argument is the name of the widget as it will be shown to the user in the Widgets administration page.

      第二个参数是窗口小部件的名称,因为它将在“窗口小部件管理”页面中向用户显示。
    3. The third argument is an associative array with the following keys:

      第三个参数是具有以下键的关联数组:

      1. classname – The entire widget along with the title will be placed within a <li> element. This element’s class name will be set to this value.

        classname –整个小部件及其标题将放置在<li>元素内。 该元素的类名将设置为此值。

      2. description – The description of the widget as it will be shown in the Widgets Administration section.

        description –小部件的描述,将在“小部件管理”部分中显示。
    4. The fourth argument is an associative array with the following keys:

      第四个参数是具有以下键的关联数组:

      1. height – Height of the widget’s options panel.

        height –小部件的选项面板的高度。
      2. width – Width of the widget’s options panel.

        width –小部件的选项面板的宽度。

    步骤8:向WordPress注册小部件 (Step 8: Register the Widget with WordPress)

    Having defined the Widget class we have to get WordPress to treat this class as a widget definition.

    定义了Widget类后,我们必须让WordPress将此类视为小部件定义。

    First, we add a function that attaches to the widget_init hook:

    首先,我们添加一个附加到widget_init钩子的函数:

    add_action("widgets_init","myplugin_widget_init");
    

    WordPress expects all plugins and themes that want to register widgets to hook onto the widgets_init hook. The above line of code registers the myplugin_widget_init() function with the widgets_init hook. We then register the widget in the function body:

    WordPress希望所有想要注册小部件的插件和主题都可以挂接到widgets_init钩上。 上面的代码行使用widgets_init钩子注册myplugin_widget_init()函数。 然后,我们在功能主体中注册小部件:

    function myplugin_widget_init()
    {
        register_widget("Twitter_Feed_Widget");
    }
    

    The register_widget() function takes one argument – the name of the widget class.

    register_widget()函数采用一个参数–小部件类的名称。

    有关WordPress小部件的重要说明 (Important Notes on WordPress Widgets)

    WordPress Widget API Was Changed

    WordPress Widget API已更改

    Prior to version 2.8, WordPress used a different method of defining widgets. Instead of defining a widget class you had to pass the function names as callbacks to two functions – register_widget_control() and register_sidebar_widget().

    在2.8版之前,WordPress使用了另一种定义小部件的方法。 不必定义窗口小部件类,您必须将函数名称作为回调传递给两个函数– register_widget_control()register_sidebar_widget()

    These functions are deprecated and will be removed in future versions. Do not use this method to create widgets. However, you will encounter these functions in the source code of existing popular plugins.

    这些功能已被弃用,并将在以后的版本中删除。 不要使用此方法创建小部件。 但是,您将在现有流行插件的源代码中遇到这些功能。

    Cache Widget Output

    缓存小部件输出

    Some dynamic widgets consume much bandwidth, CPU and/or other resources to display its content. For example, the Twitter Feed widget relies on the user’s Tweet RSS feed provided by Twitter. Downloading the feed every single time the widget is shown will overload Twitter’s server. This will result in the tweet feed loading unreliably.

    一些动态窗口小部件消耗大量带宽,CPU和/或其他资源来显示其内容。 例如,Twitter Feed小部件依赖于Twitter提供的用户的Tweet RSS feed。 每次显示小部件时下载提要将使Twitter的服务器超负荷。 这将导致推文供稿加载不可靠。

    Instead if the feed was updated only once every 5 or 10 minutes the Twitter feed will always be available. This will avoid throttling of your WordPress blog’s web server by Twitter’s. The Twitter Feed Widget plugin in the example above has been implemented such that the feeds are fetched only once every 5 minutes.

    相反,如果提要每5或10分钟仅更新一次,那么Twitter提要将始终可用。 这将避免Twitter限制您的WordPress博客的Web服务器。 上面示例中的Twitter Feed Widget插件已实现,因此每5分钟仅提取一次Feed。

    Add Enclosing Markup and Identifiers

    添加封闭的标记和标识符

    Widgets generated by plugins will be placed in the regions of many different themes. Insanely useful though your widget may be, it will be a blot on the face of a website if it stands out looking out of place.

    插件生成的小部件将放置在许多不同主题的区域中。 尽管您的窗口小部件可能非常有用,但是如果它看起来格格不入,它将成为网站表面的污点。

    Enclosing all of the elements that your widget shows in a <div> or <span> element and providing them appropriate class and id attributes can help themers to customize the look and feel of your widget to suit the visual background in which it is placed.

    将小部件显示的所有元素包含在<div><span>元素中,并为它们提供适当的classid属性,可以帮助用户自定义小部件的外观,以适合其放置的视觉背景。

    小部件使用户的生活更轻松 (Widgets Make Users’ Lives Easier)

    WordPress is the world’s most popular blogging platform because of the ease of use. Prior to implementation of widgets, users had to open up the theme files and then insert code at the appropriate location to add new features to the sidebar. That was fine when most bloggers were very tech-savvy.

    由于易用性,WordPress是世界上最受欢迎的博客平台。 在实施小部件之前,用户必须打开主题文件,然后在适当的位置插入代码以向边栏添加新功能。 当大多数博主非常精通技术时,这很好。

    Whether you are creating plugins for a client or for public release, the Widgets are a way to put control in the hands of bloggers who may not be as technically proficient as you and make the experience of using your software a lot better. Widgets help users get the most out of your plugin without risky and daunting edits to their WordPress theme.

    无论您是为客户端创建插件还是为公共发行版创建插件,小部件都是一种将控制权交到可能不如您在技术上精通的博客作者手中的一种方法,并使使用软件的体验更好。 小部件可帮助用户充分利用您的插件,而无需对其WordPress主题进行冒险和艰巨的编辑。

    翻译自: https://www.sitepoint.com/define-your-own-wordpress-widgets/

    wordpress 自定义

    上一篇: hexo搭建github.io博客

    下一篇: 修改