Оcenka-BEL.com - безплатни онлайн тестове, пробни изпити, видео уроци и помощ при писане на задания от литературно и хуманитарно естество

Creating a Plugin That Consumes a Web API in WordPress

Публикувано: 2018-09-29 18:56:45

In this tutorial, we are going to build a plugin that provides a shortcode which would show either all links or links for particular tag(s) that a user has in the Delicious.com’s bookmarking platform. Each post or page of the user can theoretically show the links of a different user because we will require the username and password of the user with attributes (probably not the best idea out there, a wiser way would be to add a configuration interface in the admin dashboard).
Creating a Plugin That Consumes a Web API in WordPress

Also, the shortcode can be invoked from within the WordPress code itself by using the do_shortcode() function. For example, this would allow hardcoding the links for a particular user in the post’s template but changing the tags that would be queried to be the words in the post’s title.

What’s new?

We will show how to make AJAX calls with the WordPress API and how to authenticate yourself through HTTP Basic Auth while making the request and our plugin will use its own stylesheet.

Read Also: Adding Custom Design or Functionality to WordPress Pages and Posts

The Plugin

Firstly, we define the header of our plugin with all metadata about it:

 

1

2

3

4

5

6

7

8

9

10

<?php

/*

Plugin Name: Show Delicious Links

Plugin URI: https://www.phpgang.com

Description: This plugin adds a shortcode which would show all Delicious links for a given tag and user

Author: PHPGang

Version: 0.1

Author URI: https://www.phpgang.com

License: GPL2

*/

Then, we hook our plugin to the initilization of WordPress and add hook ourselves to the wp_enqueue_scripts action which would call our register_delicious_styles method which will add our custom stylesheet.

 

1

2

3

4

5

6

7

8

defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

 

class showDeliciousLinks {

    public function __construct() {

        add_action("init", array($this, 'add_delicious_links'));

        add_action( 'wp_enqueue_scripts', array($this,'register_delicious_styles'));

 

    }

We register a stylesheet named delicious and provide the link to our stylesheet with wp_register_style. Afterwards, we add the stylesheet with the name that we have chosen to the required stylesheets withwp_enqueue_style.

 

1

2

3

4

5

6

public function register_delicious_styles() {

 

            wp_register_style( 'delicious', plugins_url( 'delicious/show-delicious-links.css' ) );

            wp_enqueue_style('delicious');

 

    }

The method that is called when WordPress initializes just adds a shortcode to the WordPress back-end pinpointing which method to execute when the shortcode is present.

 

1

2

3

4

5

6

7

8

9

public function add_delicious_links() {

        add_shortcode('delicious', array($this,'add_links_to_post'));

    }

public function add_links_to_post($atts) {

 

        if (isset($atts['user']) || isset($atts['password'])) {

            $username = $atts['user'];

            $password = $atts['password'];

            $tag = isset($atts['tag']) ? $atts['tag'] : "";

When the shortcode is invoked, we check if there is an attribute called user and an attribute called password. If so, we store some variables. Notice that the tag is optional and defaults to an empty string (which would get all links).

Then, we make a get request to the Delicious API with wp_remote_get and add an Authorization header to the request with the base64 encoded value of the username and password. We get only the body of the request with wp_remote_retrieve_body

 

1

2

3

4

5

$body = wp_remote_retrieve_body(wp_remote_get("https://api.delicious.com/v1/posts/get?tag=$tag", array(

                'headers' => array(

                    "Authorization" => "Basic " . base64_encode("$username:$password")

                )

            )));

The body of the response contains XML so we process it with SimpleXML:

 

1

2

3

4

5

6

7

$xml = new SimpleXMLElement($body);

            $linksArray = array();

            foreach ($xml->post as $link) {

                $linksArray[] = "<a class='btn btn-md btn-default' href='" . $link['href'] .  "'>" . $link['description'] . "( " .

                    str_replace(" ", ", ", $link['tag']  ) . " ) </a>";

            }

            $return = "<div class='delicious-links'>";

We create and array, loop over each link and store it in an array with a particular formatting. Then, we create a $return variable containing a div. Notice that we place some classes for easier styling.

 

1

2

3

4

5

6

7

8

$return .= '<p class="lead"> <a class="delicious-profile" href="https://delicious.com/' . $username . '">' .  $username . '\'s </a> Links in Delicious';

 

            if ($tag) {

                $return .= 'with the tag <span class="delicious-tag">' . $tag  . '</span></p>';

            }

            else {

                $return .= "</p>";

        }

We add a link to the user’s profile in Delicious (whose links are displayed) and if only links for particular tag were selected, we show the tag.

 

1

2

3

4

5

6

7

            foreach ($linksArray as $link) {

                 $return .= $link;

            }

            $return .= "</div>";

 

            return $return;

        }

Finally, in the end we loop over the array with links and add them to the bottom of $return’s content and actually return the variable.

 

1

2

3

4

5

6

7

else {

            return "<p class='lead'> No user or password provided to Show Delicious Links. Please add <em>user</em> and <em>password</em> attributes with your data. </p>";

        }

    }

}

 

new showDeliciousLinks();

If the username or password were not present in the attributes of the shortcode, we display an error.

In the end, we instantiate our class.

Preview

Here is the moment where we add the shortcode to a post on our WordPress site:
delicious-before

And here is how it looks like with some simple styles in our front-end:

delicious-after

Conclusion

You have seen WordPress enables you to customize almost anything using its API – You can create plugins, edit themes, add styles to the page from within plugins, use an API for AJAX calls and much more.

What you have not seen is how to persist data in a database with WordPress and how to create a menu in the admin dashboard. We will discuss the first thing next (adding to the WordPress database with the Options API).

 

 

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.bizfacebooktwitter

Article source: https://www.phpgang.com/creating-a-plugin-that-consumes-a-web-api-in-wordpress_1304.html

-->