Table of Contents
Key Takeaways
Reasons for URL Shortening
Acquiring a Google URL Shortener API Key
Plugin Directory and Files
Create a Plugin Settings Page
An Overview of the Google URL Shortener API
Displaying a Shortened URL in a Meta Box
Displaying the Short URL in the Front End
Popular URL Shortener Plugins in the WordPress.org Plugin Directory
Conclusion
Frequently Asked Questions (FAQs) about Creating a URL Shortener Plugin for WordPress
What is a URL shortener plugin and why do I need it for my WordPress site?
How does a URL shortener plugin work?
Can I customize my shortened URLs?
Is it possible to restore the ‘Get Shortlink’ button in WordPress?
Are there any free URL shortening plugins for WordPress?
How can I track the performance of my shortened URLs?
Can I use a URL shortener plugin if I’m not tech-savvy?
Can a URL shortener plugin improve my SEO?
Can I use a URL shortener plugin for my affiliate links?
Are there any risks associated with using a URL shortener plugin?
Home CMS Tutorial WordPress Create a URL Shortener Plugin for WordPress

Create a URL Shortener Plugin for WordPress

Feb 17, 2025 am 11:29 AM

Create a URL Shortener Plugin for WordPress

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.

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

Key Takeaways

  • The tutorial provides a step-by-step guide on how to create a URL shortening plugin for WordPress using Google’s URL Shortener API. This plugin can be beneficial for platforms with character limits, printed materials, and QR codes.
  • To use the Google URL Shortener API, an API key is required. This key is used by Google to track your application and can be acquired through the Google Developers Console.
  • The tutorial also explains how to create a settings page for the plugin where administrators can enter the URL Shortener API key. The API key is stored as a WordPress option with the name url-shortener-input-field.
  • The plugin created displays the shortened URL in a meta box in the post edit screen and below every post on the front end. It works seamlessly with the Google URL shortener web service and doesn’t request a new URL each time, instead, it stores it once it’s retrieved.

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:

  • 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.
  • Printed books or display signage will often use shortened URLs as they are easy to be read and type.
  • QR codes have a character limit. Very long URLs don’t fit, therefore shortening of the URL is required.

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.

Here are the steps to acquire your API key:

  • Visit Google Developers Console.
  • Select an existing project or create a new one.
  • In the left sidebar, click and expand APIs & auth.
  • Next, click APIs. In the list of APIs, make sure the status is ON for the 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.

Plugin Directory and Files

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

1

2

--url-shortener

      -url-shortener.php

Copy after login
Copy after login

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

1

2

--url-shortener

      -url-shortener.php

Copy after login
Copy after login

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:

1

2

3

4

5

6

7

8

9

<span><span><?php

</span></span><span>

</span><span><span>/*

</span></span><span><span>Plugin Name: URL Shortener

</span></span><span><span>Plugin URI: http://www.sitepoint.com

</span></span><span><span>Description: Create's a Shortened URL of every post.

</span></span><span><span>Version: 1.0

</span></span><span><span>Author: Narayan Prusty

</span></span><span><span>*/</span></span>

Copy after login

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

This is what the settings page should look like:

Create a URL Shortener Plugin for WordPress

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.

Here’s what a sample request looks like:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

<span><span><?php

</span></span><span>

</span><span><span>function url_shortener_settings_page()

</span></span><span><span>{

</span></span><span>    <span>add_settings_section("section", "Enter Key Details", null, "url-shortener");

</span></span><span>    <span>add_settings_field("url-shortener-input-field", "API Key", "url_shortener_input_field_display", "url-shortener", "section"); 

</span></span><span>    <span>register_setting("section", "url-shortener-input-field");

</span></span><span><span>}

</span></span><span>

</span><span><span>function url_shortener_input_field_display()

</span></span><span><span>{

</span></span><span>   <span>?></span>

</span>        <span><span><span><input</span> type<span>="text"</span> name<span>="url-shortener-input-field"</span> value<span>="<span><?php echo get_option('url-shortener-input-field'); ?></span>"</span> /></span>

</span>   <span><span><?php

</span></span><span><span>}

</span></span><span>

</span><span><span>add_action("admin_init", "url_shortener_settings_page");

</span></span><span>

</span><span><span>function url_shortener_page()

</span></span><span><span>{

</span></span><span>  <span>?></span>

</span>      <span><span><span><div</span> class<span>="wrap"</span>></span>

</span>         <span><span><span><h1</span>></span>URL Shortener Setting<span><span></h1</span>></span>

</span> 

         <span><span><span><form</span> method<span>="post"</span> action<span>="options.php"</span>></span>

</span>            <span><span><?php

</span></span><span>               <span>settings_fields("section");

</span></span><span>               <span>do_settings_sections("url-shortener");

</span></span><span>               <span>submit_button();

</span></span><span>            <span>?></span>

</span>         <span><span><span></form</span>></span>

</span>      <span><span><span></div</span>></span>

</span>   <span><span><?php

</span></span><span><span>}

</span></span><span>

</span><span><span>function menu_item()

</span></span><span><span>{

</span></span><span>  <span>add_submenu_page("options-general.php", "URL Shortener", "URL Shortener", "manage_options", "url-shortener", "url_shortener_page");

</span></span><span><span>}

</span></span><span>

</span><span><span>add_action("admin_menu", "menu_item");</span></span>

Copy after login

Here is the sample response looks like:

1

2

3

4

<span>POST https://www.googleapis.com/urlshortener/v1/url

</span><span>Content-Type: application/json

</span>

<span>{"longUrl": "https://www.sitepoint.com/"}</span>

Copy after login

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

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.

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

1

2

3

4

5

<span>{

</span> <span>"kind": "urlshortener#url",

</span> <span>"id": "http://goo.gl/fqsT",

</span> <span>"longUrl": "https://www.sitepoint.com/"

</span><span>}</span>

Copy after login

Here’s how this code works:

  • We created a meta box using the add_meta_box function.
  • We’re retrieving the long URL of the post using the get_permalink() function.
  • 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.
  • 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.

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

Create a URL Shortener Plugin for WordPress

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

<span>function url_shortener_meta_box_markup($object)

</span><span>{

</span>   <span>$key = get_permalink($object->ID);

</span>

    <span>if(get_option('url-shortener-input-field', '') != "")

</span>   <span>{

</span>       <span>if(get_option($key, "") != "")

</span>       <span>{

</span>           <span>echo get_option($key, "");

</span>           <span>return;

</span>       <span>}

</span>

        <span>$url = 'https://www.googleapis.com/urlshortener/v1/url';

</span>      

        <span>$result = wp_remote_post(

</span>           <span>add_query_arg(

</span>               <span>'key',

</span>               <span>get_option('url-shortener-input-field'),

</span>               <span>'https://www.googleapis.com/urlshortener/v1/url'

</span>           <span>),

</span>           <span>array(

</span>               <span>'body' => json_encode(array('longUrl' => esc_url_raw($key))),

</span>               <span>'headers' => array( 'Content-Type' => 'application/json')

</span>           <span>)

</span>       <span>);

</span>

        <span>if(is_wp_error($result)){echo "Error"; return;}

</span>

        <span>$result = json_decode($result['body']);

</span>       <span>$shortlink = $result->id;

</span>

        <span>update_option($key, $shortlink);

</span>

        <span>echo $shortlink;

</span>   <span>}

</span><span>}

</span>

<span>function url_shortener_meta_box()

</span><span>{

</span>    <span>add_meta_box("url-shortener-meta-box", "Shorten URL", "url_shortener_meta_box_markup", "post", "side", "default", null);

</span><span>}

</span>

<span>add_action("add_meta_boxes", "url_shortener_meta_box");</span>

Copy after login

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.
  • 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.

Here is how it looks on front end:

Create a URL Shortener Plugin for WordPress

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

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.

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.

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.

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.

Frequently Asked Questions (FAQs) about Creating a URL Shortener Plugin for WordPress

What is a URL shortener plugin and why do I need it for my WordPress site?

A URL shortener plugin is a tool that helps you create shorter, more manageable URLs for your WordPress posts and pages. These shortened URLs are easier to share on social media, in emails, and other platforms. They also make your links look cleaner and more professional. If you have a WordPress site with long and complex URLs, a URL shortener plugin can greatly improve your user experience and SEO.

How does a URL shortener plugin work?

A URL shortener plugin works by creating a unique, shorter version of your original URL. When a user clicks on the shortened URL, they are redirected to the original long URL. This process is seamless and does not affect the user’s browsing experience. The plugin also tracks the number of clicks on the shortened URL, providing valuable data for your marketing efforts.

Can I customize my shortened URLs?

Yes, most URL shortener plugins allow you to customize your shortened URLs. You can add your own keywords to make the URLs more meaningful and relevant. This not only makes your URLs easier to remember but also improves your SEO.

Yes, it is possible to restore the ‘Get Shortlink’ button in WordPress. This button was removed in WordPress 4.4 but you can bring it back by using a plugin or adding a code snippet to your theme’s functions.php file.

Are there any free URL shortening plugins for WordPress?

Yes, there are several free URL shortening plugins available for WordPress. Some of the popular ones include URL Shortify, Pretty Links, and Bitly. These plugins offer basic URL shortening features and are a good starting point if you are new to URL shortening.

How can I track the performance of my shortened URLs?

Most URL shortener plugins provide analytics features that allow you to track the performance of your shortened URLs. You can see how many times a URL has been clicked, the geographical location of the users, the referral sources, and more. This data can help you understand your audience better and optimize your marketing strategies.

Can I use a URL shortener plugin if I’m not tech-savvy?

Absolutely! Most URL shortener plugins are designed to be user-friendly and do not require any technical knowledge. They come with easy-to-use interfaces and detailed instructions. If you can navigate your WordPress dashboard, you can use a URL shortener plugin.

Can a URL shortener plugin improve my SEO?

Yes, a URL shortener plugin can improve your SEO. Shortened URLs are easier for search engines to crawl and index. They also improve user experience by making your links more manageable and shareable, which can boost your site’s ranking in search engine results.

Yes, you can use a URL shortener plugin for your affiliate links. In fact, it’s highly recommended. Shortened URLs look cleaner and more professional, which can increase click-through rates and conversions. Some plugins also allow you to add a nofollow attribute to your affiliate links, which is good for SEO.

Are there any risks associated with using a URL shortener plugin?

While URL shortener plugins offer many benefits, there are also some risks. For example, if the plugin’s server goes down, your shortened URLs may stop working. Also, some users may be wary of clicking on shortened URLs because they can’t see the destination URL. Therefore, it’s important to choose a reliable plugin and use shortened URLs judiciously.

The above is the detailed content of Create a URL Shortener Plugin for WordPress. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners Apr 17, 2025 am 08:25 AM

Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

How to display child categories on archive page of parent categories How to display child categories on archive page of parent categories Apr 19, 2025 pm 11:54 PM

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

How to get logged in user information in WordPress for personalized results How to get logged in user information in WordPress for personalized results Apr 19, 2025 pm 11:57 PM

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo();  function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

How to adjust the wordpress article list How to adjust the wordpress article list Apr 20, 2025 am 10:48 AM

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

Is WordPress easy for beginners? Is WordPress easy for beginners? Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

How to sort posts by post expiration date in WordPress How to sort posts by post expiration date in WordPress Apr 19, 2025 pm 11:48 PM

In the past, we have shared how to use the PostExpirator plugin to expire posts in WordPress. Well, when creating the activity list website, we found this plugin to be very useful. We can easily delete expired activity lists. Secondly, thanks to this plugin, it is also very easy to sort posts by post expiration date. In this article, we will show you how to sort posts by post expiration date in WordPress. Updated code to reflect changes in the plugin to change the custom field name. Thanks Tajim for letting us know in the comments. In our specific project, we use events as custom post types. Now

How to display query count and page loading time in WordPress How to display query count and page loading time in WordPress Apr 19, 2025 pm 11:51 PM

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin

Can I learn WordPress in 3 days? Can I learn WordPress in 3 days? Apr 09, 2025 am 12:16 AM

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.

See all articles