官术网_书友最值得收藏!

The master plugin outline

After looking over the examples on Digg.com and trying out our own proof of concept, we know what we're aiming for, so let's think through the structure of the PHP code that is required. When you write your own plugins, it's a great habit to sketch an outline of the main components before you start any serious coding because it will force you to identify problems and establish a structure. Keep in mind there are many different ways in which a plugin could be written, so don't be discouraged if your outline differs from ours.

We know our plugin needs an information header and either the add_action() or the add_filter() functions. We also want to test the WordPress version in use and we're going to outline some of the helper functions we expect we'll need to achieve all of this. To help organize our thoughts, we are going to sketch an outline for our plugin by creating some PHP comments in the file that will become our plugin. Our plugin will slowly become functional as we replace those comments with working functions. Let's get started!

Create a folder for your plugin inside /wp-content/plugins. We're naming our plugin Digg This, so the folder will be named digg-this—we have simply replaced spaces with dashes to come up with a valid folder name. Next, create an index.php file inside your plugin's folder. This index.php will contain your plugin's information header, and we will refer to it as your plugin's "main" file.

Many WordPress developers use a file named after the plugin as their plugin's "main" file, for example, digg-this.php, but we find it more intuitive to use index.php instead. As a web developer, you should already be accustomed to looking for this common file any time you scan through a directory. It may seem overly nitpicky when we are writing plugins that only have a couple files, but once your plugin grows to include multiple files, it can become increasingly difficult for you or others to find your plugin's "main" file. Here is the code we've saved inside of /wp-content/plugins/digg-this/index.php:

<?php
/* Information Header Goes here */ 

// include() or require() any necessary files here...

// Settings and/or Configuration Details go here...

// Tie into WordPress Hooks and any functions that should run on load.

// "Private" internal functions named with a leading underscore
function _diggthis_get_post_description() { }
function _diggthis_get_post_media_type() { }
function _diggthis_get_post_title() { }
function _diggthis_get_post_topic() { }
function _diggthis_get_post_url() { }

// The "Public" functions
function diggthis_add_js_to_doc_head() { }
function diggthis_check_wordpress_version() { }
function diggthis_get_button() { }

/* EOF */

That's the skeletal framework of our plugin, and it's a simple outline you can copy for similar plugins. This code should execute without errors, even though it doesn't do anything yet because our functions are empty. Regardless, you should be able to get a decent idea about how the plugin will work just by looking at this outline—we've used descriptive function names that give an idea of what each function will do. As discussed in the previous section, we have prepended "diggthis" to each function's name to help avoid naming collisions.

You can see that we've created three "public" functions to correspond with the three main things we want this plugin to do. We want it to add some JavaScript to the document head, we want it to generate a valid Digg button, and we also want it to test the version of WordPress in use. The public functions represent the main tasks for our plugin, and they are the functions that will be tied to a WordPress event.

Our "private" functions are meant to assist the public functions. Technically, they aren't private functions per se, but we are isolating them as functions that will be called by one of the "public" functions instead of being called directly. Notice that the names of these functions too begin with an underscore. It is common practice to use a leading underscore to identify functions that should be considered "private", for "internal use only". The private functions we have outlined will help the diggthis_get_button() function by getting the component parts needed to create the button: title, description, and URL. Just to be clear, the private functions we have outlined are a product of the Digg API. If Digg offered a way to transmit a post's author, for example, we would have included a corresponding _diggthis_get_post_author() function to isolate the task of getting the author's name into its own function.

Lastly, notice that we have alphabetized our functions by name for better organization.

Note

In this chapter, we are not using object oriented code, so we are not enforcing any permissions on our functions. We are referring to some functions as "public" and others as "private" merely as a way to help distinguish between primary functions and helper functions. In later chapters, we will use PHP classes and we will implement true public and private functions.

Now that we've outlined our script with comments and empty functions, let's start filling in the gaps. Here are all the areas in our plugin outline that we need to address:

  • The plugin information header
  • Adding JavaScript to the head
  • Adding a link to the post content
  • Adding a button template
  • Getting the post URL
  • Getting the post title
  • Getting the description
  • Getting the media type
  • Getting the topic

As we work through this chapter, we will show small bits of code that are meant to replace individual sections within the master plugin outline. This is intended to allow you to focus on one section of the code at a time.

The plugin information header

We know from the previous chapter that each plugin requires an information header before it shows up in WordPress' plugin administration panel. You can copy and modify the plugin header from the Hello Dolly plugin. Take a moment to customize it and save the result. The following is the plugin header we're using in our /content/wp-content/plugins/digg-this/index.php file:

/*
Plugin Name: Digg This
Plugin URI: http://www.tipsfor.us/
Description: This plugin will add a "Digg This" button link to each post on your WordPress site. 
Author: Everett Griffiths
Version: 0.1
Author URI: http://www.tipsfor.us/
*/

In your browser—information header

Remember that this header information is what causes the plugin to show up on WordPress' radar, so as soon as you've saved the file, you should be able to see it in the WordPress plugin administration screen. Before you go any further, check to ensure that your plugin is now showing up in the plugin administration page.

Note

If your future plugin has more than one PHP file, the plugin information header should be placed only in your main file, the one which will include() or require() the other plugin PHP files.

Before you continue, try activating your plugin to ensure that you do not have any syntax errors. It should work, even though it doesn't do anything yet. It is critical to start testing your script early and often. This helps you catch any errors more quickly!

Adding a link to the post content

Let's begin by focusing on modifying the post content so we can append a clickable link. It can be a challenge to know whether you need to use an action or a filter, but experience will teach you. If we examine our options in the WordPress Codex about filter references (http://goo.gl/whqA) and action references (http://goo.gl/qAps), eventually we can narrow our choices down to the the_content filter. This, by the way, is exactly the same filter we demonstrated in the previous chapter. As this is a filter and not an action, we will use the add_filter() function to reference it, and the custom function that we reference must accept an input and return an output. We've already earmarked the diggthis_get_button() as the one that will generate the button link, so we'll reference it by name in the add_filter() function.

The following is how we've edited our /content/wp-content/plugins/digg-this/index.php file:

add_filter('the_content', 'diggthis_get_button');

// [ . . . ]
/**
* Adds a "Digg This" link to the post content.
*
* @param     string   $content   the existing post content
* @return   string   appends a DiggThis link to the incoming $content.
*/
function diggthis_get_button($content) {
   return $content . '<a class="DiggThisButton DiggMedium"></a>';
}

Documenting our functions

You may have noticed that we used a special syntax for documenting the diggthis_get_button() function. We are using a PHP equivalent to the often-emulated Javadoc syntax, which is a standard syntax used for documenting functions so that your comments can be automatically converted to HTML pages. The principle is similar to Wikipedia formatting or BBCode, both of which use special symbols to specify various HTML elements. The PHPDoc syntax isn't strictly necessary, but since it is a common feature of a lot of open source PHP code, we will be using it throughout this book.

Ironically, the documentation on how to use the PHPDoc syntax is confusing and hard to follow. The official quick start is here (http://goo.gl/5CyZg), but we find the third-party tutorial at http://goo.gl/oTARc to be much more to the point and easier to follow.

No matter which syntax you use, make sure you document your functions clearly by including a brief overview of what the function does, specifying the input parameters, and specifying the value returned. Adding proper documentation to your code is a "time" investment that will save you (and others) lots of time in the long run, so please don't neglect it!

In your browser—linking to the post content

Save your file, then try refreshing your homepage. At first, everything might look the same, but try viewing the source HTML and verify that the Digg anchor tag is appearing after your post content.

Congratulations! It doesn't look like much yet and it doesn't quite work, but a little bit of JavaScript will bring it to life.

Adding JavaScript to the head

From our proof of concept, we learned that the Digg button needs to have some special JavaScript in the HTML document head. Although we could simply paste the necessary JavaScript into our template files, that defeats the purpose of dynamically adding it via a plugin. Besides, we want a solution that doesn't break when we switch templates.

As we've already done this a couple of times, you might be ready to scan through the available actions and filters in the WordPress Codex to find a viable event you can hook into. If you did that, you might come to the conclusion that using the wp_head action would be your ticket to making this work. It's true that the wp_head action would allow you to print the necessary HTML into the head of your pages, but that's actually not the recommended way of accomplishing this.

When working with plugins in any CMS, it is a common need to add both JavaScript and CSS to augment your plugin – the scripts expect to have certain JavaScript and CSS available to them in order to function correctly. WordPress, like other CMS's, has dedicated a few API functions designed explicitly to help solve this problem: wp_register_script() and wp_enqueue_script() . Together, these functions allow you to include an external JavaScript file exactly once. When used correctly, they prevent you from including the same file multiple times. That's important with JavaScript because many plugins might require the same JavaScript library, but including the same file multiple times can cause conflicts in the same way as redeclaring PHP functions. It's also inefficient to include the same file multiple times, so WordPress' functions here are an effective solution.

Our fist task then is to get the necessary JavaScript into a separate file. If you have working JavaScript inside a <script> tag, you can put its contents into an external file and reference it using the src attribute. Create a new file named digg.js and paste the contents of the <script> tag into it. Here is what we have added to our newly created digg-this/digg.js file:

(function() {
var s = document.createElement('SCRIPT'), s1 = document.getElementsByTagName('SCRIPT')[0];
s.type = 'text/javascript';
s.async = true;
s.src = 'http://widgets.digg.com/buttons.js';
s1.parentNode.insertBefore(s, s1);
})();

To include this on our pages, we would typically add something like this to our document head:

<script type="text/javascript" src="http://yoursite.com/plugins/digg-this/digg.js"></script>

In order to have WordPress do this automatically for us, we are going to make use of the aforementioned wp_register_script() and wp_enqueue_script() as well as the plugins_url() function, which helps us generate the correct URL to our new JavaScript file:

function diggthis_add_js_to_doc_head() { 
   $src = plugins_url('digg.js', __FILE__);
   wp_register_script( 'diggthis', $src );
   wp_enqueue_script( 'diggthis' );
}

The function plugins_url() generates a URL to the digg.js file inside of our plugin's folder when we pass it the __FILE__ constant, which PHP interprets as the path and name of the current file. Now we have a function that will cause the necessary JavaScript file to be loaded, but we need to tie this to a WordPress event so that this function executes. The event to which we want to tie this is the init action that fires when WordPress is initialized.

// Tie into WordPress Hooks and any functions that should run on load.
add_action('init','diggthis_add_js_to_doc_head');

When we've finished this, our index.php file looks like the following:

<?php
/*------------------------------------------------------------------------------
Plugin Name: Digg This
Plugin URI: http://www.tipsfor.us/
Description: This plugin will add a "Digg This" button link to each post on your WordPress site. 
Author: Everett Griffiths
Version: 0.1
Author URI: http://www.tipsfor.us/
------------------------------------------------------------------------------*/ 


// include() or require() any necessary files here...

// Settings and/or Configuration Details go here...

// Tie into WordPress Hooks and any functions that should run on load.
add_filter('the_content', 'diggthis_get_button');
add_action('init', 'diggthis_add_js_to_doc_head');


// "Private" internal functions named with a leading underscore
function _diggthis_get_post_description() { }
function _diggthis_get_post_media_type() { }
function _diggthis_get_post_title() { }
function _diggthis_get_post_topic() { }
function _diggthis_get_post_url() { }

// The "Public" functions
/**
* Add the local digg.js to the <head> of WordPress pages
*
* @return   none   adds HTML to the document <head>
*/

function diggthis_add_js_to_doc_head() { 
   $src = plugins_url('digg.js', __FILE__);
   wp_register_script( 'diggthis', $src );
   wp_enqueue_script( 'diggthis' );
}
function diggthis_check_wordpress_version() { }

/**
* Adds a "Digg This" link to the post content.
*
* @param     string   $content   the existing post content
* @return   string   appends a DiggThis link to the incoming $content.
*/
function diggthis_get_button($content) {
   return $content . '<a class="DiggThisButton DiggMedium"></a>';
}


/* EOF */

If you haven't already, activate this plugin and then visit the homepage of your site. You should now see a functioning Digg button. Try viewing the source HTML and verify that the Digg JavaScript is being added to the head. You should see something like the following show up in your document head when you view the source HTML:

<script type='text/javascript' src='http://yoursite.com/wp-content/plugins/digg-this/digg.js?ver=3.0.4'></script>

Tricky, eh? We are now dynamically modifying our pages and we have achieved basic functionality! If you are developing locally on your own desktop computer, you may get some errors when you try to submit a link to Digg: Unable to access this content. This is normal—Digg is trying to connect to your site, but if you are developing locally, your site is not publicly available, so it throws this error.

If you get any other errors, the PHP information printed to the screen should help you track down their source.

Making our link dynamic

We have the basic functionality in place, but our link doesn't yet send any data to Digg.com. Remember from Digg's documentation that we can supply each link with a URL, a title, a description, a media type, and a topic. That's why we set up those other functions.

In order to pass all that additional information, we need to modify the format of our link, so we have to refer back to Digg's documentation. Arguably, we could have done this right off the bat in our proof-of-concept page, but it was good to first test the basic functionality. Let's revisit our proof_of_concept.html page and try to use a "fully qualified" link that passes along the extra attributes.

While tinkering with Digg's format on our proof_of_concept.html, we realized a couple of things that may throw you off. First, submitting a page is a two-part process, and only after Digg has evaluated your submission can you see whether or not the attributes you passed actually came through. In short, it takes a bit of mouse work to test if it is working properly.

Secondly, Digg uses "&amp;" to separate name/value pairs in their URL instead of the traditional "&". This might seem perplexing, but it has to do with URL encoding, and "&amp;" is actually correct.

We had to piece together various parts of the Digg documentation to get what we wanted, but when we finished, our proof_of_concept.html file contained a link that looked like this:

<a class="DiggThisButton DiggMedium"  rev="news, tech_news">
<span style="display:none">This site will make you smarter.</span>
</a>

In your browser—dynamic links

Before going further, take a moment to verify that the static proof-of-concept still works and that all attributes are passed correctly. You can log into Digg.com using your Facebook or Twitter account. If everything was passed correctly, you should see a page on Digg.com that has all the information you specified in your proof-of-concept link.

Unfortunately, at the time of writing, we had problems getting all attributes to pass correctly. In particular, the description and the topic that we defined in our proof of concept never showed up on Digg.com; they had to be re-entered manually. Rather than trying to tell you that web service integrations like this are always peaches and cream, this can be a good reality check: API's do not always work as advertised. It's fairly common that the documentation is incomplete or the examples don't work. If this frustrates you, then it should be a strong motivation for you to make sure that your functions work and are documented properly.

Adding a button template

Now that we've tested it, let's update our diggthis_get_button() function so that we can pass information dynamically using the full link format. We will now take the opportunity to reference the other functions, even though they still are empty. As always, it's important to keep your code as organized as possible, so we're going to use the PHP sprintf() function to format our link string and replace instances of "%s" with values returned by our functions. If you're not familiar with sprintf(), take a moment to look over its manual page: http://php.net/manual/en/function.sprintf.php. It's a really useful function for cleanly formatting strings.

We are also going to make use of a PHP constant. PHP constants are declared using the define() function. Constants are declared in the global namespace, so like functions, you have to be careful that their names are unique. Unlike variables, they cannot be overwritten once defined, so they are perfect for configuration details that should not be changed.

We're going to create a PHP constant in the section of our plugin that we have earmarked for configuration details:

// Settings and/or Configuration Details go here...
define ('DIGGTHIS_BUTTON_TEMPLATE', 
   '<a class="DiggThisButton DiggMedium" 
      
      rev="%s, %s">
      <span style="display:none">
         %s
      </span>
      </a>');

This constant contains instances of "%s", which will be replaced by PHP's sprintf() function. Here's our updated diggthis_get_button() function, now using the sprintf() function. Notice that we have used PHP's urlencode() function to encode the values for $url and $title:

/**
* Adds a "Digg This" link to the post content.
*
* @param     string   $content   the existing post content
* @return   string   appends a DiggThis link to the incoming $content.
*/
function diggthis_get_button($content) {
   $url       = urlencode( _diggthis_get_post_url() );
   $title      = urlencode( _diggthis_get_post_title() );
   $description   = _diggthis_get_post_description();
   $media_type   = _diggthis_get_post_media_type();
   $topic      = _diggthis_get_post_topic();   
   
   return $content . sprintf(
      DIGGTHIS_BUTTON_TEMPLATE, 
      $url, 
      $title, 
      $media_type, 
      $topic, 
      $description);
}

There are more concise ways of writing this function that would have required fewer variables, but here we are striving for clarity. Never optimize your functions prematurely—your first priorities should always be functionality and readability. A more conventional way to construct the link would have been via concatenation, as shown below:

return '<a class="DiggThisButton DiggMedium"
       . $url . '&title=' . $title. '"
      rev="' . $media_type . ', ' . $topic . '"
      <span style="display:none">
         ' . $description. '
      </span>
      </a>';

Concatenation works, but can you see how much more difficult it is to read? Particularly, keeping track of the quotes and periods is prone to error, so we prefer the sprintf() function. Its first argument is the string or template that contains placeholders (that is %s). The following list of parameters correspond to values that will replace the placeholders; the first instance of %s will be replaced by the value of $url, and the second %s by the value of $title and so on. It can be an elegant way to keep your code clean.

Getting the post URL

Let's start fleshing out the helper functions that retrieve the link's URL, title, and other attributes. Can you see the logic of our approach here? We've framed the script in a way that lets us develop gradually and test as we go, function by function.

We're going to start introducing some elements from the WordPress API to help us get the information we need about each post. Our primary source of information here is the WordPress function reference: http://codex.wordpress.org/Function_Reference.

Can you find a function that retrieves a post's URL? We did it using the get_permalink() function. By default, it will return the URL of the current post, which is what we want.

/**
* Gets the URL of the current post.
*
* @return   string   the URL of the current post.
*/
function _diggthis_get_post_url() {
return get_permalink();
}

It's worth mentioning that there are multiple ways we could have gone about this. We have opted to use the built-in WordPress functions whenever possible because we feel they offer a cleaner interface to the application. It is entirely possible, however, to rely on WordPress variables instead. Look at the following variation on the same function:

function _diggthis_get_post_url() {
   global $post;
   return get_permalink($post->ID);
}

Notice our use of the global keyword. This has nothing to do with the notorious PHP security vulnerability that arises when register globals are enabled. Rather, it is a command which instructs PHP to inherit the globally scoped variable of that name, rather than creating a new locally scoped variable. In other words, WordPress already has a global $post variable floating around, and we want to use it. The $post variable is actually an object, and it has all kinds of information about the current post. If you are curious, try temporarily printing its contents using print_r() and observing the result when you refresh the page:

function _diggthis_get_post_url() {
   global $post;
print_r($post); exit; // <-- temporarily add this line if you're curious!
return get_permalink($post->ID);
}

Once you've seen what's contained in the $post object, be sure to delete or comment out the print_r and the exit lines.

Accessing post data directly from the $post object has some advantages, but in general we feel it's clearer to rely on WordPress' accessor methods to retrieve post attributes.

We could have forgone our custom function altogether, since the only thing it did was to reference a single WordPress function. We did construct a sensible outline, though, and we have isolated a single function dedicated to a single purpose, and that clarity is useful.

In your browser—getting the post URL

Once you have implemented the _diggthis_get_post_url() function you should be able to save your work and then refresh your home page in your browser. By examining the source of the HTML, you should be able to see some values coming through. In the HTML of our page, we can see that we are now getting a value for the URL:

<a class="DiggThisButton DiggMedium"         rev=", ">
<span style="display:none"></span></a>

We still have a lot of empty attributes, though, so let's keep going!

Getting the post title

We're going to do something very similar for the _diggthis_get_post_title() function. First, we'll find a viable WordPress API function that can return the post's title, and then we'll add it to our function earmarked for the purpose:

/**
* Gets the title of the current post.
*
* @return   string   the title of the current post.
*/
function _diggthis_get_post_title () {
$id = get_the_ID();
return get_the_title($id);
}

As before, save the result and check the result in your browser.

Getting the description

Getting the post description is slightly more complicated because Digg requires that the excerpt be no longer than 350 characters. There are some built-in WordPress functions that return excerpts, but nothing does exactly what we want. So, we're going to roll up our sleeves and write our own function that grabs the first 350 characters of the content.

We have to think a bit more ahead, though. Digg wants only text, but our content may contain HTML tags or WordPress shortcodes (more about those in a later chapter). So we need to make sure we strip all of those out of the excerpt before we count our 350 characters.

Lastly, we want to make sure that we don't chop a word in half when we return the excerpt. As we are perfectionists, we are going to ensure that only whole words are sent to Digg for their description.

The following is the function we came up with. Note that we used WordPress's strip_shortcodes() function and PHP's strip_tags() function:

/**
* Gets a short description/excerpt of the post from the content.
*
* @return   string   stripped of html tags and shortcodes.
*/
function _diggthis_get_post_description() {
   $excerpt       = get_the_content();
   $excerpt       = strip_shortcodes($excerpt);
   $excerpt       = strip_tags($excerpt);
   $excerpt       = substr($excerpt,0, 350);
   $words_array    = explode(' ', $excerpt);
   $word_cnt       = count($words_array);
   return implode(' ', array_slice($words_array, 0, $word_cnt - 1));
}

Wow. We did some crazy stuff in there. Let's walk you through what we did. Firstly, we retrieved the post content using WordPress' get_the_content() function. Next, we removed WordPress shortcodes from the content using WordPress' strip_shortcodes() function. Shortcodes are macro codes that can appear in your post content, so they can throw off the total number of characters in a text-only excerpt. We also need to remove any HTML tags from the excerpt, so for that we used PHP's strip_tags() function. After those functions have operated on the content, we should have only raw text, of which we need only 350 characters. The next few functions help us prevent chopping a word in half—if we had simply grabbed 350 characters from the raw content, chances are that we'd end up with half a word at the end of our excerpt, and that's just as bad as half a worm in your apple. The way we prevent chopping a word in half means that we grab the first 350 characters using PHP's substr() function, then we effectively count the words using PHP's explode() function, which converts the string to an array of words. Since the last word in that array might be half a word, we omit the last word from the excerpt using the count() function and the array_slice() function. Finally, we glue the array of words back together using the implode() function. Our solution here might be somewhat complicated, but it is thorough enough to cover our bases.

Getting the media type

The media type is not something we are going to support in this first version, so we are going to return a static value from our function:

/**
* Get the media type for the current post
*
* @return   string   a valid media type: news, image, or video.
*/

function _diggthis_get_post_media_type() {
return 'news';
}

"Shenanigans!" you might be saying. "That's not legit!" Calm down. It is actually quite common for programmers to earmark certain functionality as "Future" or "To-Do". We should be happy that we've isolated this particular functionality into its own function, and if we so choose, we can at a later date make this plugin dynamically determine the media type. However, for now, we're going to leave it alone.

It would be a great exercise for the reader to figure out a way to determine whether a post's media type was "image" or "video". We can give you a hint: search for "post types".

Getting the post topic

The post topic is something that we could return statically as well, but there is the possibility that our post has been grouped into a category that might match up favorably with a Digg topic. From Digg's documentation, we can see a list of viable topics: arts_culture, autos, baseball, and so on. If our site is predominantly about baseball, then we could set this to a static value and forget about it, but let's do this instead: if one of a post's categories matches up with one of Digg's topics, we'll use that as the topic, but if not, we'll fall back on a default topic.

To accomplish this plan, we're going to use another PHP constant in our script in the area we've reserved for settings and configuration details:

// Must be one of the allowed Digg topics: http://about.digg.com/button
define ('DIGGTHIS_DEFAULT_TOPIC','tech_news');

For our site, we've decided to use tech_news as our default. Like before, we're going to look through the available WordPress functions to use in our _diggthis_get_post_topic() function. We can get all of a post's categories using WordPress' get_categories() function. Then we need to see if any of them match up with the viable Digg topics. The following is how we did it:

/**
* Checks current post categories to see if any WP Category is a viable 
*   Digg topic; if yes, return the first match. Otherwise, the 
*   DIGGTHIS_DEFAULT_TOPIC will be returned.
*
* @return   string   a viable Digg topic.
*/
function _diggthis_get_post_topic() {

   $digg_topics_array = array(
      'arts_culture','autos','baseball','basketball','business_finance',
      'celebrity','comedy','comics_animation','design','educational',
      'environment','extreme_sports','food_drink','football','gadgets',
      'gaming_news','general_sciences','golf','hardware','health',
      'hockey','linux_unix','microsoft','mods','motorsport',
   'movies','music','nintendo','odd_stuff','olympics','other_sports',      'pc_games','people','pets_animals','playable_web_games','playstation',
      'political_opinion','politics','programming','security','soccer',
      'software','space','tech_news','television','tennis','travel_places',
      'world_news','xbox',);
   
   $category_array = get_categories();
   
   foreach ( $category_array as $cat ) {
      // WP replaces spaces w '-', whereas Digg uses '_'
      $category_name = preg_replace('/ \-/','_',$cat->category_nicename);
      if ( in_array ( $category_name, $digg_topics_array ) ) {
         return $category_name;
      }
   }
   
   // if no match, then fall back to the default
   return DIGGTHIS_DEFAULT_TOPIC;
}

We have used WordPress' get_categories() function to retrieve all the categories that the current post has been placed in. We can iterate through these categories and use the PHP in_array() function to determine if a category matches any of Digg's topics. We have to manipulate WordPress' categories a bit so they match up with the Digg topics: we replace spaces and dashes with underscores. We have opted to use PHP's powerful preg_replace() function for this purpose, but we could have used the str_replace() function as well:

$replace_me = array(' ', '_');
$category_name = str_replace($replace_me, '_', $cat->category_nicename);

Although str_replace() and similar functions are simpler to understand, the preg_replace() function offers a flexible solution using Perl's powerful regular expressions. Regular expressions represent a huge topic in and of themselves, so we can't get too far into their syntax. However, if you ever use other program languages, it's more likely that you will end up using the Perl syntax, so we favor its use.

In your browser—title, description, and topic

Once you complete this function, your Digg button should be fully functional! Try refreshing your home page and clicking your Digg button. Verify whether the title, description, and the topic come through to the Digg page when you click on the button. If you are developing locally on your computer, remember that Digg will complain that the URL is not properly formatted, so you can temporarily modify your _diggthis_get_post_url() function to return the URL of a publicly available page:

function _diggthis_get_post_url() {
   return "http://www.tipsfor.us/";    // <-- temporary for testing
   // return get_permalink();
}

Be sure to change the function back to normal after testing.

主站蜘蛛池模板: 宁城县| 星子县| 射洪县| 鞍山市| 河南省| 临澧县| 巴彦淖尔市| 阳朔县| 札达县| 高要市| 林甸县| 岫岩| 梅河口市| 饶平县| 大英县| 雅安市| 徐闻县| 盐城市| 隆德县| 淄博市| 东丽区| 民权县| 佳木斯市| 黎城县| 扎囊县| 舒城县| 定结县| 绥芬河市| 固始县| 阳江市| 靖西县| 正定县| 龙江县| 林口县| 错那县| 富阳市| 平顶山市| 屏边| 民丰县| 斗六市| 阿拉尔市|