Using WP-Syntax with a Twenty-Ten Child Theme

Ok sorry, another esoteric post about software to interrupt my usual musings, but it may help out someone who runs into this issue in the future and goes googling for an answer (since I tried doing so myself unsuccessfully)…

In writing my previous post, about Twitter Widget Pro, I needed to embed some software into the text to illustrate the code changes I’d made, and that meant finding a way to format the text of the software appropriately. A little poking around revealed several plugins for WordPress that offer this capability, two of which seemed to be the most likely candidates, SyntaxHighlighter Evolved and WP-Syntax. The first seemed to have a few more features, but I did a little checking and discovered a few “cool kids” who were using WP-Syntax, so I decided to give that a try.

As with other plugins I’ve used, installation was no problem. I downloaded the plugin’s zip file, unpacked it and uploaded it to my blog’s plugin directory on the server. From the WordPress plugin admin screen I activated the plugin and I was good to go. Or so I thought.

When writing the text of a blog post in ‘html’ edit mode, the WP-Syntax plugin is used to format a chunk of code by wrapping the text of the code with <pre> and </pre> tags and specifying the language and optionally the starting line number as attributes. So something like this –

<pre lang="php"> 
  <?php
    $sometext = "Hello World";
  ?>
<\pre>

will generate this –

<?php
  $sometext = "Hello World";
?>

This is all good. However I ran into a couple of problems. Initially the text of the code being displayed in the box was way larger than I intended it to be. The reason was that the styling for the <pre> tags was coming from the stylesheet for my WordPress theme, rather than that associated with the plugin.

It wasn’t immediately obvious to me why this was so since I could see from firebug that the plugin’s stylesheet was being loaded correctly, after the theme’s stylesheet. However, eventually I realized that there was an issue with the specificity of the rules in each stylesheet.

The plugin stylesheet is located at <root>/wp-content/plugins/wp-syntax/wp-syntax.css. The blog uses a child theme derived from the standard WordPress “Twenty-ten” theme and so styling for the theme as a whole is controlled by two stylesheets, the parent located at <root>/wp-content/themes/twentyten/style.css and the child located at <root>/wp-content/themes/markmthomson/style.css (the latter imports the former and is the one that is explicitly loaded by the browser).

The plugin stylesheet and the Twenty-ten parent theme’s stylesheet both had rules with conflicting style specifications pointing at elements within the <pre>…</pre> code block. However many of the relevant rules in the Twenty-ten theme’s stylesheet are defined in the context of the ‘#content’ id, e.g. –

#content pre {
  font-size: 15px;
  line-height: 21px;
}

In contrast the rules in the plugin’s stylesheet were defined in the context of the ‘.wp-syntax’ class, e.g. –

.wp_syntax pre {
  ...
  font-size: 12px;
  line-height: 1.333;
  ...
}

When two style rules apply to the same element, in general there are several factors that determine which one has precedence. There’s a reasonably full discussion of the issue in this TechRepublic article, while the official W3C explanation is here, but the short version is that when multiple rules apply to the same element, e.g. from different stylesheets, the specificity of the rules (which I’ll explain in a moment) is evaluated first and the most specific rule is the one that’s applied. If multiple rules have the same specificity, the one declared last will apply (and the exact meaning of ‘last’ is explained in the TechRepublic article).

There is a good explanation of specificity here. Basically, each css rule’s selector (e.g. like ‘.wp_syntax pre‘ in the earlier example) is assigned a numerical value that reflects the specific combination of html elements, ids and classes that make up the selector. In determining this value, each html element contributes a value of 1, each class adds 10 and each id adds 100 (in whatever numerical base is chosen). The higher the total for a given rule, the more specific that rule is considered to be.

Based on this, it’s clear that theme rules containing the #content id in their selectors will outweigh those from the WP-Syntax plugin that contain only the .wp-syntax class. This is why the formatted code blocks were being styled by the theme and not by the plugin.

The solution to this problem has two parts. First, it is necessary to modify the plugin’s css rules so that they each include the #content context in their selector as well as .wp-syntax. For example –

#content .wp_syntax pre {
  ...
  font-size: 12px;
  line-height: 1.333;
  ...
}

According to the plugin’s usage documentation, customization of the plugin’s style can be accomplished by copying the css file from the plugin into the blog theme’s template directory and making modifications to it there. However a complication not mentioned in the documentation arises when the theme is a child of another one, as it is in my case.

In principle, one would want to apply such modifications to the child theme rather than the parent. I discovered, however, that placing a modified plugin css file in the child theme’s template directory did not have the desired effect. Instead, it turned out to be necessary to add wp-syntax.css to the directory for the parent Twenty-ten theme and make the required modifications there.

Although this worked, it’s not a perfect solution. Part of the point of the way WordPress child themes work is to decouple modifications in style from the definition of the original theme. Adding the wp-syntax style sheet to the parent violates this principle.

I posted a query on the WordPress support forum to see if anyone had run into this issue and had a better solution and sure enough someone (the anonymous OddOneOut) was able to recommend a much better approach.

The cause of the problem is the way WP-Syntax defines where the browser should look for the plugin’s stylesheet. This happens in a php function wp_syntax_head() defined in the file wp-syntax.php, which is located in <root>/wp-content/plugins/wp-syntax/. The code for this function looks like this –

function wp_syntax_head()
{
  $css_url = WP_PLUGIN_URL . "/wp-syntax/wp-syntax.css";
  if (file_exists(TEMPLATEPATH . "/wp-syntax.css"))
  {
    $css_url = get_bloginfo("template_url") . "/wp-syntax.css";
  }
  echo "\n".'<link rel="stylesheet" href="' . $css_url . '" type="text/css" media="screen" />'."\n";
}

What’s happening here is that the plugin checks to see if there is a wp-syntax.css file within the theme’s template directory, and if there is it creates the correct link to that file and inserts it into the html file that will be read by the browser. However the constant TEMPLATEPATH refers to the parent theme’s template, not that of the child. Similarly, the function get_bloginfo(“template_url”) returns the uri for that directory.

We need, instead, to check whether there is a wp-syntax.css file in the theme’s actual template directory, which in my case will be that for the child theme. The constant STYLESHEETPATH refers to that directory, and the function get_bloginfo(“stylesheet_directory”) returns the uri for that directory. The code should therefore be modified as follows –

function wp_syntax_head()
{
  $css_url = WP_PLUGIN_URL . "/wp-syntax/wp-syntax.css";
  if (file_exists(STYLESHEETPATH . "/wp-syntax.css"))
  {
    $css_url = get_bloginfo("stylesheet_directory") . "/wp-syntax.css";
  }
  echo "\n".'<link rel="stylesheet" href="' . $css_url . '" type="text/css" media="screen" />'."\n";
}

With this change, the customized plugin css file can now be placed in the child theme’s template directory, and the formatted code block will be styled correctly.

Posted in Website | 2 Comments

Adding Retweets to Twitter Widget Pro

I mentioned yesterday that I have added my twitter feed to the website using the WordPress widget plugin ‘Twitter Widget Pro‘. Although it seemed to be working ok, I noted that the number of tweets being displayed was different from what I’d specified in the widget’s settings. Subsequently I discovered that the reason was connected with another problem that I didn’t initially realize I had – the widget was not displaying my ‘retweets’, i.e. twitter comments from other people I follow that I add to my own feed. However, it was apparently including the missing retweets in its total count of the tweets it was retrieving, causing the number of tweets displayed to be wrong.

Checking the support forum over at xavisys.com revealed that a number of others have mentioned this problem, going back at least as far as January this year. Given this apparent limitation, I could have gone and looked for a different plugin, but I decided instead to see if I could figure out why retweets weren’t being displayed.

The problem turned out to be with the way the plugin invokes the Twitter API. This happens in the php function _getFeedUrl() in file wp-twitter-widget.php, which is located in the plugin directory <root>/wp-content/plugins/twitter-widget-pro. The original code looks like this –

629
630
631
632
633
634
635
636
637
638
639
640
private function _getFeedUrl($widgetOptions, $type = 'json', $count = true) {
	if (!in_array($type, array('rss', 'json'))) {
		$type = 'json';
	}
	if ( $count ) {
		$num = ($widgetOptions['hidereplies'])? 100:$widgetOptions['items'];
		$count = sprintf('?count=%u', $num);
	} else {
		$count = '';
	}
	return sprintf('http://twitter.com/statuses/user_timeline/%1$s.%2$s%3$s', $widgetOptions['username'], $type, $count);
}

The code that generates the URI used to retrieve the twitter data in JSON format can be seen at line 639. In my case this would produce something like:

http://twitter.com/statuses/user_timeline/markmthomson.json?count=8

However, when I looked at the Twitter API documentation, I wasn’t able to find an example that matches the pattern shown in this example. Instead, the URI that does appear to provide the required data looks like this –

http://api.twitter.com/1/statuses/user_timeline.json?screen_name=markmthomson&include_rts=true&count=8

Critically, the query parameter ‘include_rts=true’ is explicitly required in order for the list of tweets returned to include retweets. Evidently the plugin was using an older version of the API that doesn’t support this capability. In order to generate the URI for the published API, I modified the code as follows –

629
630
631
632
633
634
635
636
637
638
639
640
private function _getFeedUrl($widgetOptions, $type = 'json', $count = true) {
	if (!in_array($type, array('rss', 'json'))) {
		$type = 'json';
	}
	if ( $count ) {
		$num = ($widgetOptions['hidereplies'])? 100:$widgetOptions['items'];
		$count = sprintf('&count=%u', $num);
	} else {
		$count = '';
	}
	return sprintf('http://api.twitter.com/1/statuses/user_timeline.%1$s?screen_name=%2$s&include_rts=true%3$s', $type, $widgetOptions['username'], $count);
}

Note that there are changes to both line 635 and line 639. With this modification, the plugin now displays retweets and the count is correct. However, there is one problem remaining…

The text of some retweets retrieved in this way is truncated and terminated with an ellipsis (I’m guessing because the leading attribution text “RT <screen_name>” that gets added probably puts the tweet over the 140 character limit). Further examination of the JSON data returned by Twitter revealed that the full text of each retweet is actually present (without the attribution prefix), but it is stored in a different part of the object, specifically within an embedded object referenced by a key named “retweeted_status”. This object also includes data about the author of the retweet. What this means is that if the JSON object corresponding to a single retweet is represented by a php variable “$tweet”, the full text of the tweet can be accessed as “$tweet->retweeted_status->text”, while the author’s screen name is given by “$tweet->retweeted_status->user->screen_name”.

The html used to render the tweets is generated in function display() in wp-twitter-widget.php. From that function, the following is a fragment of the loop over tweets that generates the content of each tweet –

502
503
504
505
506
foreach ($tweets as $tweet) {
	if ( $args['hidereplies'] != 'true' || empty($tweet->in_reply_to_user_id)) {
		// Set our "ago" string which converts the date to "# ___(s) ago"
		$tweet->ago = $this->_timeSince(strtotime($tweet->created_at), $args['showts'], $args['dateFormat']);
		$entryContent = apply_filters( 'widget_twitter_content', $tweet->text );

The modification required to retrieve the full text of retweeted tweets is as follows –

502
503
504
505
506
507
508
509
510
511
foreach ($tweets as $tweet) {
	if ( $args['hidereplies'] != 'true' || empty($tweet->in_reply_to_user_id)) {
		// Set our "ago" string which converts the date to "# ___(s) ago"
		$tweet->ago = $this->_timeSince(strtotime($tweet->created_at), $args['showts'], $args['dateFormat']);
		if ( isset($tweet->retweeted_status) ) {
			$tweet_text = "RT @".$tweet->retweeted_status->user->screen_name.":".$tweet->retweeted_status->text;
		} else {
			$tweet_text = $tweet->text;
		}
		$entryContent = apply_filters( 'widget_twitter_content', $tweet_text );

Note the lines 506-510 have been added and line 511 has been modified by replacing “$tweet->text” with “$tweet_text”. With this modification, retweeted tweets are now rendered correctly. Problem solved!

Posted in Software Development, Website | 13 Comments

Twitter Feed Added to Sidebar

I started using Twitter a few weeks back and I have now added my recent tweets to the sidebar over on the right (at least if you’re reading this on the website and not in a feedreader). I am using the Twitter Widget Pro plugin for WordPress developed by Xavisys. Installation was simple – I just downloaded and unzipped the plugin directory ‘twitter-widget-pro’ on my PC and then uploaded it to the wp-content/plugins directory on my server. I activated the plugin from the WordPress plugins admin screen and then on the widgets admin screen dragged and dropped it into place on the sidebar and adjusted the configuration to grab my feed from Twitter. Sweet. The only problem I have at the moment is that I’ve set it to display the last eight tweets and it’s actually only giving me six. Oh well. No biggie.

I’ve also reduced the overall font size a smidge for all the content on the blog. Not completely convinced about the result as it currently stands and I may yet come up with a different solution, but with the extra information density in the sidebar, the old font size just made the overall page layout a little hard to look at.

I’ve actually had a Twitter account for over a year, but have never found much reason to use it. However I’ve started following a few folks recently and have also started tweeting from time to time myself – mostly pointers to interesting stuff I find online. It was kind of cool to be able to send a question this morning to the well-known economist Nouriel Roubini about something he had tweeted and get a response from him in just a few minutes.

Posted in Website | Leave a comment

David Corn

Of self-acknowledged liberals in the media, one who I generally enjoy listening to quite a lot is Chris Matthews on MSNBC’s Hardball show – though not so much some of his guests, whether conservative or liberal. The following clip from Matthews’ show tonight features one liberal whose comments I found particularly objectionable – David Corn of Mother Jones.

Corn comments as follows on the possibility of Sarah Palin running for President, following a short clip from an interview she did recently with Barbara Walters…

Pat Buchanan’s old friend Ronald Reagan, there was a saying associated with him, “do it for the gipper”. With Sarah Palin it looks like her saying is “do it for the hell of it.”

Look, I am not any kind of fan of Sarah Palin. She may have some positive instincts and great charisma as a public figure, but I personally think she lacks the kind of intellectual resources and judgment needed to cope with the demands of being President. However Corn’s comments go way, way beyond any serious attempt to assess her ability to be a good President. Instead he chooses to go straight for a cheap shot at her character that is in no way supported by, or even connected with, the interview with Barbara Walters. It is pure political hackery of the worst kind.

Posted in Media, Politics | Leave a comment

Shields and Brooks on QE

I always enjoy watching the regular commentary segment with Mark Shields and David Brooks on PBS Newshour on Fridays (though I find David Brooks to be the more interesting by far). This week I was struck by comments that both of them made about quantitative easing (QE). They both admitted that they don’t understand enough about the issue to know whether the Federal Reserve’s strategy is right or wrong.

The video is below and the section about QE starts at 9:35. Brooks’ comment is at 10:00 and Shields’ is at 10:42. I’m not necessarily criticizing these guys – I’ve been spending quite a bit of time trying to assess the pros and cons myself – but it is interesting that two of the nation’s leading news analysts feel they don’t know enough to form an opinion about one of the key economic issues of the day.

Posted in Economics, Media | Leave a comment

St Lukes Vote Details

I wondered a few days ago how many of the councillors who made the decision to approve the St Lukes mall expansion in Auckland live nearby. We now know: one – sort of.

The minutes (pdf) of the November 17 Council meeting are now online (currently here, but I suspect that link won’t be permanent) and they show that out of the 20 councillors and the mayor, 16 voted for the change to the District Plan, and of those the only one you could argue lives close to the mall is Christine Fletcher. She lives 4.2 km away in Bourne St, Mt Eden and represents the Albert-Eden-Roskill ward, which includes St Lukes.

All of those who voted for the change and the wards they represent are –

  • Arthur Anae – Manukau
  • Cameron Brewer – Orakei
  • Len Brown – Mayor
  • Alf Filipaina – Manukau
  • Chris Fletcher – Albert-Eden-Roskill
  • Michael Goudie – Albany
  • Ann Hartley – North Shore
  • Penny Hulse – Waitakere
  • Des Morrison – Franklin
  • Calum Penrose – Manurewa-Papakura
  • Noelene Raffills – Whau
  • Jami-Lee Ross – Howick
  • Sharon Stewart – Howick
  • John Walker – Manurewa-Papakura
  • Penny Webster – Rodney
  • George Wood – North Shore

Only five voted against the change to the Plan. They were –

  • Cathy Casey, who lives in Allendale Ave, Mt Albert. She is the closest councillor to St Lukes at 2.8 km away. Like Fletcher, she also represents Albert-Eden-Roskill.
  • Sandra Coney – Waitakere.
  • Mike Lee – Waitemata & Gulf.
  • Richard Northey – Maungakiekie-Tamaki.
  • Wayne Walker – Albany.
Posted in New Zealand, Politics, Urban Design | Leave a comment

The Control Instinct

NZ Finance Minister, Bill English, is reported as staying that the Westpac Bank “should front up to its customers and explain why it is paying its New Zealand boss a record $5.59 million”.

Really? Do we really need the Government trying to decide what individuals in the private sector are worth? Do we require other companies to justify their employees’ salaries to their customers? As the Herald points out, the Westpac CEO’s salary is not the highest in the country and is broadly consistent with what CEOs of other large companies in NZ are paid.

Do Westpac’s customers feel they are getting a raw deal from the bank? Are many of them switching to other banks because of it? Is the Westpac board dissatisfied with the value they get from their CEO? Are the shareholders complaining? If Mr English thinks there is a problem with the value customers are getting from the bank, is he really saying that NZ does not have a competitive banking sector? Why is that?

Posted in New Zealand, Politics | Leave a comment

St Lukes Expansion Approved

The NZ Herald reports that the proposed expansion of the St Lukes mall in Auckland that I wrote about recently has been approved. I feel sad for the local residents. I wonder how many of the councilors who made the decision live nearby?

Posted in New Zealand, Urban Design | Leave a comment

NZ Government Support for Optimist Worlds

I was rather surprised today to read (NZ Herald and Government press release) that the NZ Government is giving NZ$150,000 to the Optimist World Championships (a junior sailing competition for those who don’t know), which are to be held at Napier, December 31, 2011 – January 10, 2012.

The rationale given in the press release is that this is an ‘investment’ designed to promote the Hawkes Bay economy. Given that I’m a sailing fanatic, I guess I might be expected to be happy about this, but frankly I think it raises some questions that really need to be answered before I would be ready to congratulate anyone.

Having myself been involved this year in the organization of a fairly major North American sailing regatta, I find the size of this grant pretty remarkable. Our event took place over one week and involved 127 catamaran sailors, mostly from across North America plus several from Europe and South America. Competitors raced in four different classes on two separate courses. This event was essentially self funded by entry fees, commercial sponsorship, merchandise sales and raffles and had a total budget of around US$30,000.

The Optimist event is larger – an estimated 250 sailors for 11 days, but the entry fees are NZ$1500 each, providing minimum revenue of $375,000 – yeah, in the vicinity of 10 times the size of our budget. And the Government is giving an additional $150,000, raising the minimum revenue (before any commercial sponsorship) of $525,000.

I find this quite staggering. I have written to Gerry Brownlee, the Minister for Economic Development, asking for the bid documentation, so I can see both the event budget and the economic analysis used to justify his decision to make this investment. I will report what I find out here on the blog.

Posted in New Zealand | Leave a comment

Phil Goff on Accident Compensation

I’m a little slow getting to this (what else is new), but nonetheless feel a need to comment… I was disappointed to read in the NZ Herald last Sunday comments by NZ’s Opposition Leader, Phil Goff, criticizing the Government over a consultation document released by the NZ Accident Compensation Corporation.

The document (not referenced by the Herald :( but I believe it’s this one, from the ACC Levy Consultation site) includes a number of new proposals, of which several have, broadly speaking, two goals – one is to allow the ACC to adjust individual levies for different people and employers to reflect different amounts of risk, while the other would allow people to opt for lower levies in return for lower accident compensation benefits.

Both ideas seem to me generally to be within the bounds of things worth giving thoughtful consideration to. Unfortunately, that’s not how I would characterize Phil Goff’s reaction. Instead of commenting intelligently on the pros or cons of the substance of the proposals, he claims that the proposals are just “the Government’s way of privatising the state-owned injury insurer by ‘stealth’“. According to the Herald, he told NZPA “it was not so much the specific proposals which worried him, but what lay behind them was the Government’s desire to move to a user-pays, privatised system“.

The reason I find this disappointing is that it’s fundamentally a lazy argument. In my view, trying to attribute motive to someone, as he is doing here, is always a poor substitute for a real argument because there’s simply no way to prove that it’s either right or wrong. To make matters worse, in an attempt (I guess) to support his allegation, he tries to link the Government’s alleged motives with what he considers to be the political tactics of former National Finance Minister Ruth Richardson, stating, “This is a National Government which learned from Ruth Richardson that you don’t do it all at once but you just bring it in by stealth until people wake up and realise that the system that they once enjoyed is gone“.

Really?? The mother of the “Mother of All Budgets” was known for a cautious gradualist approach to reform? Interesting! Even if that characterization were reasonable, Ruth Richardson left office in 1993! Is this really the best argument Mr Goff can give us – linking the Government with someone who has been out of office for 17 years?

For what it’s worth, I think it’s conceivable that a coherent argument could be made that introducing a choice of lower levies for lower benefits may be a bad thing – e.g. if people on low incomes were to make that choice for reasons of financial hardship and end up with inadequate support in the event of an accident. But surely this is the point of the consultation process – to give people a chance to make these kinds of arguments. It’s unfortunate that Mr Goff has so far chosen not to have that kind of debate.

Posted in New Zealand, Politics | Leave a comment