U.S. Capitol.

Politics: It’s the Journey, not the Destination

It’s been a long time since I discussed politics here. I occasionally get into politics over on Twitter, but rarely do I write about it. I don’t consider myself a political wonk so I leave the blogging to the wonks. However, I am not exactly a political outsider either. With years under my belt in the political epicenter of the country – the Greater Washington, D.C. Region – I’m not exactly naive about the political gamesmanship that happens every day.

Now, living in Austin, Texas – the state capital, and center of political activity in the great State of Texas – it’s not like I’m unaware of the way things work on a state level either (though admittedly, I know far less about Texas politics than I do about Maryland or National politics). However, living and traveling outside of the Beltway bubble has been enlightening in how the rest of the country sees the political process.

More or less, outside the beltway, the vast majority of laypeople see politics as something that is offensive, or at minimum, charged with rhetoric, hate and something that is to be shunned in casual social scenarios. Things are so personal to the electorate that, right or left, the objective of governing is lost. The right sees the left as a bloc of people intent on taking away personal liberties, led by a man so vilified for ideas that are less written in stone, and more written in perception based on questionable, if not indiscriminately inaccurate, data.

The left is not much better. The left sees the right as a segment of the country who wants to simply obstruct every bit of progress possible, while returning the country to a racist, misogynist, hateful past.

Both of these perceptions, while steeped in some level of truth, are shams. Both highlight tendencies that reflect deeper conditions among both groups. But here’s the funny part… Both views are curated by both parties inside the beltway.

Whyever would anyone want to perpetrate these despicable ideas???

It’s funny how politics works. Politics is based entirely on manipulation and both parties (the establishment, not the people holding a voter registration card in South Dakota) are masters of it. Politics exists for the sake of power and both parties know that. Both parties also know they need each other to retain power. Both parties agree and walk in unison on 80% of issues. It’s the 20% that is a grand, choreographed display of artistic fortitude. It’s the 20% that allows the GOP to fire up their base of voters to keep keep them (or re-take) power. It’s the 20% that carries the Democrats to a 2006 and 2008 landslide based on anti-Bush sympathy and promises of Hope and Change. It’s the 20% that turns the Tea Party into a movement to be reckoned with in 2010.

Both parties know this and both parties work in lock-step to ensure this epic drama unfolds as it’s supposed to. To do so ensure that Democrats and Republicans lock-in the two party system, that benefits both of them in terms of money and power, for decades to come. To fail to do so (as in, an apathetic American public who isn’t angered by the Thème de la Jour), reveals cracks in the armor, possible loss of campaign contributions, corporate lobbying dollars, and power.

Having lived inside the Beltway, Hill staffers from both sides of the aisle put on their contorted political dance during the day, on television, radio programs, interviews and other media avenues, just to go to happy hour with their colleagues from across the aisle after hours. They are just like us in their every day life (with maybe more hectic schedules). They watch sports, go shopping, eat at restaurants, enjoy craft beers and go through their lives like all of us. The difference is, when they are at work, they are creating an elaborate illusion for the rest of the country.

The illusion is one of hatred, angst, bitter rivalries and political gamesmanship. The point: Keep the proletaria right so bent out of shape about Obama (or whoever) policies and the grassroots left looking at disgust at Republicans using parliamentary games that block Democratic initiatives.

It’s all a game.

Which brings me to the point I took a long time getting to: the GOP primaries.

Last night, I watched as Twitter exploded with chatter about Arizona and Michigan results where Mitt Romney won handily and barely, respectively. People scoffed at Santorum’s pro-life, anti-abortion stance while (inaccurately) putting out misinformation like, “If Santorum gets elected president, he’s going to take away your condoms”. Likewise, equally vilifying statements were made about Mitt Romney.

Now, I am not a partisan. I am unaffiliated with either party and I’m certainly not casting any support to the GOP candidate or to President Obama. I just don’t know who I’ll vote for in November. But I’ll tell you that watching the ongoing angst over the GOP Presidential hopefuls is both funny and tragic. It’s funny because… well, the GOP will get a 40% base no matter who gets the nomination and Obama will get his 40% base no matter who gets the nomination. It’s the 20% in the middle that will decide the race. You can get pissed off about Obama  but the historical data on election trends speaks for itself. Likewise, you can throw statements around about Romney and Santorum, but there’s no reason to believe that the election results in November will break any other way than they always have.

It’s tragic because I realize so few people sit back and enjoy the process. They lose the process through the politics. The process – the primaries as well as the other aspects of Washington work – is a beautiful work of art that has been around for centuries. The system is to be cherished. The politics not so much.

The primaries are not about elections. They aren’t even about politics. They are a mechanism of a party to determine who is going to be on the ticket for the general election (which is about politics). The rules for primaries are different between parties. The outcomes are irrelevant, except for the party internal mechanisms.

While the media does 24 hour coverage of these cycles (did ya hear Super Tuesday is coming up?!), the electorate gets more worked up into a fevered frenzy. It’s sort of like the snake charmer and the cobra where we the people are the cobra and the media and the beltway operation is the snake charmer.

So enjoy this process. Enjoy our system of government that, while not perfect, is still quite amazing. Everything that is old is new again. Everything new is fading away. It’s made up of cycles and we are just players in a grand dance.

Read More

TUTORIAL: Using WordPress’ Ajax API

WordPress has tons of APIs to do tons of things. It really does. One of the cool ones that I’ve been using a lot lately, has been around for a bit. It’s the Ajax API. Sure, you could write your own Ajaxy thing but why do that when WordPress lets you do it all very simply.

This tutorial will show you how to replicate the functionality that is presented in the “Like” button at Facebook. It assumes that you have WordPress set to require users to be logged in to take such actions. It wouldn’t make much sense for someone to not be logged in for such functionality. Obviously, you could do something else with Ajax (polls? Loading new content?) that doesn’t have the same assumption, but in this case… we’re assuming a user is logged in and the $current_user global is set.

Getting Started

Let’s start with the basic PHP class (you do write good object-oriented code, right?)

1
2
3
4
5
6
7
8
class My_Like_Button {

    function __construct()
    {
    }
}

$my_like_button = new My_Like_Button;

This code is just a basic skeleton that provides a constructor (the __construct() method, which I’ll use later. It also instantiates a new My_Like_Button object and assigns it to the $my_like_button variable for use in the global scope. Obviously, you can use whatever strikes your fancy for the class name or the global variable.

Building the HTML for the Like Button

Next, we need the basic HTML structure that will be used in our theme for the Like button. For the sake of simplicity, I’m not providing any CSS, but feel free to do as you wish. We need to add this as a new method in our class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function like_button()
{
    if( !is_user_logged_in() )
        return false;
       
    global $current_user;
       
    $html = '<form action="" method="post">
        <input type="hidden" name="like_post_id" id="like_post_id" value="'
. get_the_ID() .'">
        <input type="hidden" name="like_user_id" id="like_user_id" value="'
. $current_user->ID . '">
        <input type="button" name="like_this_post" id="like_this_post" value="Like" />
    </form>'
;
    return $html;
}

This form provides two hidden form fields using get_the_ID() and the $current_user object. Having done this (and after ensuring there is a logged in user), we can now drop this into our theme in the Loop as a template tag:

1
<?php echo $my_like_button->like_button(); ?>

Sending the Ajax Request with jQuery

This is useless by itself. We need something to handle the Ajax. But before we get there, we need to understand how Ajax works within the WordPress context.

All requests must go to wp-admin/admin-ajax.php. Forget the confusion about why you would send a front-end Ajax request to the back-end. You just do.

On the back-end, you’ll have to define functions that will hook into the Ajax API to let WordPress know how to handle the request. More on that in a minute. Let’s build some jQuery to send this to admin-ajax.php.

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
function js()
{
    wp_enqueue_script( 'jquery' );
    wp_print_scripts();
    ?>
    <script>
    jQuery(document).ready(function(){
           
        jQuery('#like_this_post').click(function(){
            var like_post_id = jQuery('#like_post_id').val();
            var like_user_id = jQuery('#like_user_id').val();
           
            jQuery.post(
                '<?php echo get_option('siteurl') . '/wp-admin/admin-ajax.php' ?>',
                {
                    action      : 'register_like',
                    user_id     : like_user_id,
                    post_id     : like_post_id,
                    _wpnonce    : '<?php echo wp_create_nonce('nonce-register_like'); ?>',
                },
                function(response) {   
                    alert(response);
                }
            );
               
        });
    });
    </script>
    <?php
}

This is just a PHP function that we can use to throw some jQuery (using the .post() method for our Ajax call) into the head. Note the nonce. You must include this for security. Additionally, you must have an action set. The action is used by WordPress to route the Ajax request.

Finally, we’re passing two extra pieces of data – user_id which is the WordPress user ID and the post_id which is the WordPress post ID of the current $post object inside the Loop. Both of these are supplied in the hidden form fields we created earlier.

Let’s add a new method for hooks and call it in our constructor, so that hooks are executed when the object is instantiated:

1
2
3
4
5
6
7
8
9
function __construct()
{
    $this->hooks();
}
   
function hooks()
{
    add_action( 'wp_head', array( $this, 'js' ) );
}

Supplying the Ajax Handler

Having hooked the jQuery into WordPress, we now need something on the other end to handle the request and return something back to our page. For this, let’s create a method called handle_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
function handle_like()
{
    global $wpdb;
    $user_id = (int) $_POST['user_id'];
    $post_id = (int) $_POST['post_id'];
       
    if( !is_user_logged_in() )
        return false;
       
    if( !wp_verify_nonce( $_POST['_wpnonce'], 'nonce-register_like' ) )
        die( 'Go away, asshole!' );
       
    /*
        Here is where we do some sort of database operation to associate
        the Like of the given post with the user who performed the action
       
        Make sure you check for errors. In order to return data, you must
        echo something that the originating page can see. True or false
        only makes sense on this page and not back there.
           
        Typically, you'd output some sort of JSON, XML or plain text.
    */

    $meta_id = add_post_meta( $post_id, 'user_liked', $user_id );
    if( !$meta_id )
        echo "Like not recorded";
    else
        echo "Like recorded";
    exit;
}

In this method, it’s important that all data be sanitized to avoid security problems. I’m performing the most basic of data security here by casting the $_POST variables for the users ID and the post ID to integers.

We’re also checking to make sure the user is logged in. This is why using the built in WordPress Ajax API is actually kind of important. If you build your own Ajax handler, there’s no way to reliable tie in to WordPress to use other APIs like the User API.

Finally, make sure you verify the nonce so you know the request is coming from a legitimate source.

The three security procedures I just listed will largely prevent SQL Injection, ensure authenticated users and eliminate the possibility of Cross Site Request Forgery (CSRF) and generally should be used in all WordPress plugin development.

Simply though, the above method takes the post ID, the user ID and creates a new record in the postmeta table. On success, it will print a success method readable by the original sending page and vica versa on failure.

Note: You must use die() or exit() at the end of the method to make sure the Ajax response exits properly.

Tying the Handler into WordPress

Now that we have a handler method to do our bidding, we need to make sure WordPress knows about it so it routes Ajax requests to the proper place. To do this, we leverage the wp_ajax_{$action} hook.

Remember earlier, while building the jQuery Ajax request, I mentioned that an action POST variable had to be set? WordPress looks to this variable to create a dynamic hook that we can use our new Ajax callback to hook into.

1
add_action( 'wp_ajax_register_like', array( $this, 'handle_like' ) );

Because our action in the js() method was set to register_like, the hook WordPress creates dynamically is wp_ajax_register_like and we can use that to hook our Ajax handler onto.

Wrapping it all Together

Easy right? Use jQuery to send data, wp-admin/admin-ajax.php to receive the Ajax request and pass it on to an appropriate handler function, and send data back to the original page. On the receiving end, you can use normal means to handle the returned data as you wish.

You can download the full code used here at Github.

Read More