热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

为WordPress创建URL缩短器插件

URLshorteningisatechniqueinwhichaURLismadesubstantiallyshorterinlengthandstilllinkstothere

URL shortening is a technique in which a URL is made substantially shorter in length and still links to the required page. This is achieved by using a redirect on a domain name that is short, which links to the web page that has the longer URL.

URL缩短是一种使URL的长度大大缩短并且仍然链接到所需页面的技术。 这是通过在短域名上使用重定向来实现的,该域名链接到具有较长URL的网页。

In this tutorial, I’ll show you how to create a URL shortening plugin for WordPress using Google’s URL Shortener API.

在本教程中,我将向您展示如何使用Google的URL Shortener API为WordPress创建URL缩短插件。

缩短网址的原因 (Reasons for URL Shortening)

Before we start building a URL shortening plugin let’s see a few examples as to why we may need this plugin:

在开始构建URL缩短插件之前,让我们看一些为什么我们可能需要此插件的示例:

  • On Twitter and some other messaging services there is a limit to number of characters a message can contain. So if you’re sending long URLs then it will occupy most of the message.

    在Twitter和其他一些消息服务上,消息可以包含的字符数有限制。 因此,如果您要发送长URL,则它将占用大部分消息。
  • Printed books or display signage will often use shortened URLs as they are easy to be read and type.

    印刷书籍或显示标牌通常会使用缩短的URL,因为它们易于阅读和键入。
  • QR codes have a character limit. Very long URLs don’t fit, therefore shortening of the URL is required.

    QR码有字符限制。 非常长的URL不适合,因此需要缩短URL。

获取Google URL Shortener API密钥 (Acquiring a Google URL Shortener API Key)

To use the Google URL Shortener API you’ll need to acquire an API Key. This API key is used by Google to keep track of your application.

要使用Google URL Shortener API,您需要获取一个API密钥。 Google使用此API密钥来跟踪您的应用程序。

Here are the steps to acquire your API key:

以下是获取API密钥的步骤:

  • Visit Google Developers Console.

    访问Google Developers Console 。

  • Select an existing project or create a new one.

    选择一个现有项目或创建一个新项目。
  • In the left sidebar, click and expand APIs & auth.

    在左侧边栏中,单击并展开APIs&auth。
  • Next, click APIs. In the list of APIs, make sure the status is ON for the Google URL Shortener API.

    接下来,单击API。 在API列表中,确保Google URL Shortener API的状态为“开”。
  • In the sidebar on the left, select Credentials. Then generate a public access key if you haven’t already. This public access key is the API key.

    在左侧的边栏中,选择“凭据”。 如果还没有,请生成一个公共访问密钥。 此公共访问密钥是API密钥。

插件目录和文件 (Plugin Directory and Files)

Our plugin will contain one directory and one file. Here is the structure:

我们的插件将包含一个目录和一个文件。 结构如下:

--url-shortener
-url-shortener.php

To make the plugin installable, we put this code in the url-shortener.php file:

为了使该插件可安装,我们将以下代码放在url-shortener.php文件中:

/*
Plugin Name: URL Shortener
Plugin URI: http://www.sitepoint.com
Description: Create's a Shortened URL of every post.
Version: 1.0
Author: Narayan Prusty
*/

创建一个插件设置页面 (Create a Plugin Settings Page)

We need to create a settings page for our plugin where administrator’s can enter the URL Shortener API key. Here is the code to create a settings page using the WordPress Settings API:

我们需要为插件创建一个设置页面,管理员可以在其中输入URL Shortener API密钥。 这是使用WordPress设置API创建设置页面的代码:

function url_shortener_settings_page()
{
add_settings_section("section", "Enter Key Details", null, "url-shortener");
add_settings_field("url-shortener-input-field", "API Key", "url_shortener_input_field_display", "url-shortener", "section");
register_setting("section", "url-shortener-input-field");
}
function url_shortener_input_field_display()
{
?>
" />
}
add_action("admin_init", "url_shortener_settings_page");
function url_shortener_page()
{
?>


URL Shortener Setting



settings_fields("section");
do_settings_sections("url-shortener");
submit_button();
?>


}
function menu_item()
{
add_submenu_page("options-general.php", "URL Shortener", "URL Shortener", "manage_options", "url-shortener", "url_shortener_page");
}
add_action("admin_menu", "menu_item");

We are storing the API key as a WordPress option with the name url-shortener-input-field.

我们将API密钥作为WordPress选项存储为名称url-shortener-input-field

This is what the settings page should look like:

设置页面应如下所示:

URL Shortner settings page

Google URL Shortener API概述 (An Overview of the Google URL Shortener API)

To shorten a long URL you need to send a POST request to the https://www.googleapis.com/urlshortener/v1/url URL with your API key and long URL.

要缩短长网址,您需要使用API​​密钥和长网址将POST请求发送到https://www.googleapis.com/urlshortener/v1/url网址。

Here’s what a sample request looks like:

这是一个示例请求的样子:

POST https://www.googleapis.com/urlshortener/v1/url
Content-Type: application/json
{"longUrl": "https://www.sitepoint.com/"}

Here is the sample response looks like:

这是示例响应,如下所示:

{
"kind": "urlshortener#url",
"id": "http://goo.gl/fqsT",
"longUrl": "https://www.sitepoint.com/"
}

Note: You cannot send more than 1 million requests using the same API key in a day.

注意:每天使用同一API密钥发送的请求不能超过一百万。

在元框中显示缩短的URL (Displaying a Shortened URL in a Meta Box)

We want to display the shortened URL in a meta box in the post edit screen. For creating a meta box, we’ll use the Meta Box API and for the URL shortening we’ll use the WordPress HTTP API.

我们想在帖子编辑屏幕的一个元框中显示缩短的URL。 为了创建一个meta box,我们将使用Meta Box API ,对于URL缩短,我们将使用WordPress HTTP API 。

Here’s the code to display our shortened URL in a meta box:

这是在元框中显示缩短的URL的代码:

function url_shortener_meta_box_markup($object)
{
$key = get_permalink($object->ID);
if(get_option('url-shortener-input-field', '') != "")
{
if(get_option($key, "") != "")
{
echo get_option($key, "");
return;
}
$url = 'https://www.googleapis.com/urlshortener/v1/url';
$result = wp_remote_post(
add_query_arg(
'key',
get_option('url-shortener-input-field'),
'https://www.googleapis.com/urlshortener/v1/url'
),
array(
'body' => json_encode(array('longUrl' => esc_url_raw($key))),
'headers' => array( 'Content-Type' => 'application/json')
)
);
if(is_wp_error($result)){echo "Error"; return;}
$result = json_decode($result['body']);
$shortlink = $result->id;
update_option($key, $shortlink);
echo $shortlink;
}
}
function url_shortener_meta_box()
{
add_meta_box("url-shortener-meta-box", "Shorten URL", "url_shortener_meta_box_markup", "post", "side", "default", null);
}
add_action("add_meta_boxes", "url_shortener_meta_box");

Here’s how this code works:

此代码的工作方式如下:

  • We created a meta box using the add_meta_box function.

    我们使用add_meta_box函数创建了一个meta框。

  • We’re retrieving the long URL of the post using the get_permalink() function.

    我们使用get_permalink()函数检索帖子的长URL。

  • Then, we’re checking if we already have a short URL of this long URL in the database as a WordPress option. If not, then we’re retrieving it using the HTTP API and storing it as a WordPress option. Otherwise we use the existing short URL.

    然后,我们正在检查数据库中是否已经有这个长URL的短URL作为WordPress选项。 如果不是,那么我们将使用HTTP API检索它并将其存储为WordPress选项。 否则,我们将使用现有的简短URL。
  • This plugin plays nicely with the Google URL shortener web service as it doesn’t request a new URL every time, instead it stores it once it’s retrieved.

    该插件可与Google URL Shortener网络服务很好地配合使用,因为它不会每次都请求新的URL,而是在检索到它后立即将其存储。

This is what the meta box looks like in post edit screen:

这是元框在帖子编辑屏幕中的样子:

Meta box in post edit screen

在前端显示短URL (Displaying the Short URL in the Front End)

We also want to display the shortened URL below every post. Here’s the code to do just that:

我们还希望在每个帖子下方显示缩短的URL。 这是执行此操作的代码:

function url_shortener_content_filter($content)
{
if($GLOBALS['post']->post_type != "post")
return;
$key = get_permalink($GLOBALS['post']->ID);
if(get_option('url-shortener-input-field', '') != "")
{
if(get_option($key, "") != "")
{
$content = $content . "

Shortern URL: " . get_option($key, "") . "

";
return $content;
}
$url = 'https://www.googleapis.com/urlshortener/v1/url';
$result = wp_remote_post(
add_query_arg(
'key',
get_option('url-shortener-input-field'),
'https://www.googleapis.com/urlshortener/v1/url'
),
array(
'body' => json_encode(array('longUrl' => esc_url_raw($key))),
'headers' => array( 'Content-Type' => 'application/json')
)
);
if(is_wp_error($result)){echo "Error"; return;}
$result = json_decode($result['body']);
$shortlink = $result->id;
update_option($key, $shortlink);
$content = $content . "

Shortern URL: " . $shortlink . "

";
}
return $content;
}
add_filter("the_content", "url_shortener_content_filter");

This is how this code works:

这段代码是这样工作的:

  • We are first checking to make sure WordPress is processing a post. If it’s a page or custom post type, then we aren’t displaying the short URL. However, if you want to display it in every page then remove the first two lines from the function code.

    我们首先检查以确保WordPress正在处理帖子。 如果是页面或自定义帖子类型,则我们不会显示简短的URL。 但是,如果要在每个页面中显示它,则从功能代码中删除前两行。
  • Then we’re doing everything the same as we did while displaying the short URL in the meta box. The only difference is that instead of echoing it, we are concatenating it to the post content.

    然后,我们将执行与在meta框中显示短URL时相同的所有操作。 唯一的区别是,我们没有将其回显,而是将其连接到帖子内容。

Here is how it looks on front end:

这是前端的外观:

Shortened URL Example

Now we’re done with building a awesome URL shortener plugin for WordPress!

现在,我们已经为WordPress构建了一个很棒的URL缩短器插件!

WordPress.org插件目录中的流行URL Shortener插件 (Popular URL Shortener Plugins in the WordPress.org Plugin Directory)

If you’d like to check out existing plugins, two of the most popular URL Shortener plugins in the WordPress.org Plugin Directory are URL Shortener and WP URL Shorten.

如果您想查看现有的插件,WordPress.org插件目录中最流行的两个URL Shortener插件是URL Shortener和WP URL Shorten 。

WP URL Shorten uses ref.li to shorten URLs. Ref.li provides real time stats and other traffic information of people visiting your site via their shortened URL.

WP URL Shorten使用ref.li来缩短URL。 Ref.li通过缩短的URL提供访问您网站的人员的实时统计信息和其他流量信息。

URL Shortener plugin lets you choose between Bit.ly, Su.pr, YOURLS, Goo.gl and many other services. This plugin can also generate QR Codes.

短网址插件可以让你Bit.ly,Su.pr,YOURLS,Goo.gl和许多其他服务之间进行选择。 该插件还可以生成QR码。

结论 (Conclusion)

In this tutorial, I’ve shown you how to easily build your own URL shortening plugin. You can now go ahead and expand on this to add more features such as QR code support and use other URL shortening services. Please share your experience with your own plugins below.

在本教程中,我向您展示了如何轻松构建自己的URL缩短插件。 现在,您可以继续进行扩展,以添加更多功能,例如QR码支持和使用其他URL缩短服务。 请在下面与您自己的插件分享您的经验。

翻译自: https://www.sitepoint.com/create-a-url-shortener-plugin-for-wordpress/




推荐阅读
  • Imtryingtofigureoutawaytogeneratetorrentfilesfromabucket,usingtheAWSSDKforGo.我正 ... [详细]
  • SpringBoot uri统一权限管理的实现方法及步骤详解
    本文详细介绍了SpringBoot中实现uri统一权限管理的方法,包括表结构定义、自动统计URI并自动删除脏数据、程序启动加载等步骤。通过该方法可以提高系统的安全性,实现对系统任意接口的权限拦截验证。 ... [详细]
  • 如何查询zone下的表的信息
    本文介绍了如何通过TcaplusDB知识库查询zone下的表的信息。包括请求地址、GET请求参数说明、返回参数说明等内容。通过curl方法发起请求,并提供了请求示例。 ... [详细]
  • PHP图片截取方法及应用实例
    本文介绍了使用PHP动态切割JPEG图片的方法,并提供了应用实例,包括截取视频图、提取文章内容中的图片地址、裁切图片等问题。详细介绍了相关的PHP函数和参数的使用,以及图片切割的具体步骤。同时,还提供了一些注意事项和优化建议。通过本文的学习,读者可以掌握PHP图片截取的技巧,实现自己的需求。 ... [详细]
  • 本文介绍了C#中生成随机数的三种方法,并分析了其中存在的问题。首先介绍了使用Random类生成随机数的默认方法,但在高并发情况下可能会出现重复的情况。接着通过循环生成了一系列随机数,进一步突显了这个问题。文章指出,随机数生成在任何编程语言中都是必备的功能,但Random类生成的随机数并不可靠。最后,提出了需要寻找其他可靠的随机数生成方法的建议。 ... [详细]
  • 本文介绍了Redis的基础数据结构string的应用场景,并以面试的形式进行问答讲解,帮助读者更好地理解和应用Redis。同时,描述了一位面试者的心理状态和面试官的行为。 ... [详细]
  • 如何使用Java获取服务器硬件信息和磁盘负载率
    本文介绍了使用Java编程语言获取服务器硬件信息和磁盘负载率的方法。首先在远程服务器上搭建一个支持服务端语言的HTTP服务,并获取服务器的磁盘信息,并将结果输出。然后在本地使用JS编写一个AJAX脚本,远程请求服务端的程序,得到结果并展示给用户。其中还介绍了如何提取硬盘序列号的方法。 ... [详细]
  • [译]技术公司十年经验的职场生涯回顾
    本文是一位在技术公司工作十年的职场人士对自己职业生涯的总结回顾。她的职业规划与众不同,令人深思又有趣。其中涉及到的内容有机器学习、创新创业以及引用了女性主义者在TED演讲中的部分讲义。文章表达了对职业生涯的愿望和希望,认为人类有能力不断改善自己。 ... [详细]
  • 本文介绍了如何在给定的有序字符序列中插入新字符,并保持序列的有序性。通过示例代码演示了插入过程,以及插入后的字符序列。 ... [详细]
  • 如何用UE4制作2D游戏文档——计算篇
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了如何用UE4制作2D游戏文档——计算篇相关的知识,希望对你有一定的参考价值。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • 本文介绍了Web学习历程记录中关于Tomcat的基本概念和配置。首先解释了Web静态Web资源和动态Web资源的概念,以及C/S架构和B/S架构的区别。然后介绍了常见的Web服务器,包括Weblogic、WebSphere和Tomcat。接着详细讲解了Tomcat的虚拟主机、web应用和虚拟路径映射的概念和配置过程。最后简要介绍了http协议的作用。本文内容详实,适合初学者了解Tomcat的基础知识。 ... [详细]
  • flowable工作流 流程变量_信也科技工作流平台的技术实践
    1背景随着公司业务发展及内部业务流程诉求的增长,目前信息化系统不能够很好满足期望,主要体现如下:目前OA流程引擎无法满足企业特定业务流程需求,且移动端体 ... [详细]
  • 本文介绍了Windows操作系统的版本及其特点,包括Windows 7系统的6个版本:Starter、Home Basic、Home Premium、Professional、Enterprise、Ultimate。Windows操作系统是微软公司研发的一套操作系统,具有人机操作性优异、支持的应用软件较多、对硬件支持良好等优点。Windows 7 Starter是功能最少的版本,缺乏Aero特效功能,没有64位支持,最初设计不能同时运行三个以上应用程序。 ... [详细]
  • 基于Axis、XFire、CXF的webservice客户端调用示例
    本文介绍了如何使用Axis、XFire、CXF等工具来实现webservice客户端的调用,以及提供了使用Java代码进行调用的示例。示例代码中设置了服务接口类、地址,并调用了sayHello方法。 ... [详细]
author-avatar
烟花宇凉
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有