Tumblelog by Soup.io
Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

September 22 2010

10:00

How to create a wordpress magazine theme using Twenty Ten – Part 2

This is part two of a short series outlining how to tweak a wordpress template to get some magazine style functionality. Part one is available here.

The copy to clipboard option


Note: If you want to copy code directly from this tutorial roll you mouse over the top, right-hand corner of the code and a little window will pop up with a copy code function.

In the previous part of this tutorial we set ourselves up to experiment with the Twenty Ten Template. So at this point you should have

  • A working installation of the wordpress.org (version 3 or above)
  • The Twenty Ten theme set as the active theme
  • A number of posts sorted in to three categories – News, Sport and Featured Article
  • The permissions for the Twenty Ten theme folder set to 666

The next step is to take a look at the files we are going to edit.

The Main Index template

If you switch to Appearance > Editor and click the Main Index Template link on the right.

You should see the following in the editor window.

[php]
/**
* The main template file.
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package WordPress
* @subpackage Twenty_Ten
* @since Twenty Ten 1.0
*/

get_header(); ?>

/* Run the loop to output the posts.
* If you want to overload this in a child theme then include a file
* called loop-index.php and that will be used instead.
*/
get_template_part( 'loop', 'index' );
?>


[/php]

We start with some comments. Notice that and see where the PHP starts and ends and you should be able to spot a few function calls. These essentially piece the page together bit by bit. For example…

[php]
get_header();
[/php]

…calls the first part of the webpage including all the HTML needed to set the page up and display the blog title and navigation. The only function that might not be immediately obvious is:

[php]
get_template_part( ‘loop’, ‘index’ );
[/php]

This function calls a template file called loop (loop.php) which contains all the information needed to get and display the list of posts on the front page. It also tells the function that this request has come from the index(homepage).

You can take a look at the loop.php template by opening it in the editor – pretty scary. But the loop is key to the way WordPress works.

What is the loop

Here’s what WordPress say about the loop:

The Loop is used by WordPress to display each of your posts. Using The Loop, WordPress processes each of the posts to be displayed on the current page and formats them according to how they match specified criteria within The Loop tags. Any HTML or PHP code placed in the Loop will be repeated on each post. When WordPress documentation states “This tag must be within The Loop”, such as for specific Template Tag or plugins, the tag will be repeated for each post.

Just to put that in to context, a standard front page would use the loop to :

  1. Get the last 10 posts in the wordpress database, sorted in date order
  2. For each of each post, get the headline, content and other related content and create the HTML to display it
  3. Repeats that process until all ten posts are done.

This might sound complicated but it’s actually got a lot simpler in WordPress 3.0. In earlier versions the loop would be part of the index page. Instead of the relatively simple file above, you would have all the loop content in there as well. This meant a lot more to pick through to sort out a page. You could argue that it’s just shifted the complex stuff to another file. But as we’ll see, it does make life easy for us.

The bottom line is that getting a grip on the loop is the key to tweaking a template. So let’s have a go.

Backing-up

Make sure you have the Main Index Template file loaded in to the editor

  • Copy all the content
  • Open your text editor and paste the content in to a new document.

This is your back up of the file. If anything goes wrong, you can just copy and paste the original file content back. I would advise that you do this at regular intervals. Just copy and paste in to the file and you’ll have a big file with each iteration of the file.

Adding another loop

Now that we are backed up we can edit a file. When working I tend to have two tabs open so I can switch between the backend, where I’m editing, and the front end to see the results.

So, in the backend make sure your in the editor and your looking at the Main Index Template file .

Just after:

[html]

[/html]

Add the following:

[php]
$my_query = new WP_Query('category_name=Featured Story&showposts=1');
while ($my_query->have_posts()) : $my_query->the_post();
?>


[/php]

Click the Update file button to save the changes.

The new loop content

The result should be that the title for the most recent post in the Featured Story category appears at the top of the page with the original list of posts below. It won’t work like a link, that comes next.

[php]
$my_query = new WP_Query(‘category_name=Featured Story&showposts=1′);
[/php]

The first line defines a variable or temporary store for information called $my_query (In PHP variables always start with the $ sign). The ‘value’ of that variable is the result of a new database query which uses the WP_Query function to ask for 1 post from the Featured Story category. By asking for one, you’ll get the latest one.

[php]
while ($my_query->have_posts()) : $my_query->the_post();
[/php]

The second line starts a loop. It says that while our variable has content (posts) spit out the content of the post so we can do something with it. In this case we display the title:

[php]

[/php]

Notice the mix of PHP and HTML here. The H2 tag formats the title but its the function the_title() that gets the content. The last bit…

[php]

[/php]

…ends the loop and lets wordpress get on with the rest of the page.

Because we stipulated one post in the query the loop only goes round once. You could try adding more posts to the Featured Story category and adjusting the showposts value to see how it handles more than one post.

Dealing with errors

oops, you've missed something

When you bash around with PHP you will eventually come across an message like this when you look at your page. Don’t panic! All it means is that you’ve missed a bracket or other element in the code. Juts go back and check through. The error message even gives you a clue to what and where you made the mistake.

Adding more content

We can pull in more content from the post using some simple template tags.

Add the following after the_title() code:

[php]

[/php]

So the the bit you’ve added should resemble

[php]
$my_query = new WP_Query('category_name=Featured Story&showposts=1');
while ($my_query->have_posts()) : $my_query->the_post();
?>



[/php]

The added excerpt

Update the file and have a look at the results. You should get the title with a short excerpt and a continue reading link. Check out the wordpress codex entry for the_excerpt() function to see what’s going on.

It’s that simple!

Making the title in to a link

The last part for today is to get the title to work as a link. Here’s the basic code:

[php]

The formatted title

Conclusions

By adding another loop at the start of the index page we are able to control what which posts are displayed. Using template tags means we can pick which bits of the post we display. The simple nature of the new WordPress 3.0 main index template means we don’t have huge amounts of code to wade through and if we panic we can simply delete the stuff we have added and the original template is intact.

We still have some issues of styling and we also want to add some thumbnails to our posts. But if you look at the list of posts on the front page you will notice we have another problem – the featured post we called in our new loop is repeated in the original loop content. So quite a few things to sort out.

So tomorrow we will look at how we can replace the old loop all together and how to avoid that duplication. Then, in the final part we’ll look at how we can add the thumbnail and style the content to improve the look and feel. For now, heres the complete file we are left with (with comments added by me) :

[php]
/**
* The main template file.
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package WordPress
* @subpackage Twenty_Ten
* @since Twenty Ten 1.0
*/

get_header(); ?>

/* This is the new loop to display a featured story.
* It creates a variable and then loads all the posts that match the query.
*/

$my_query = new WP_Query('category_name=Featured Story&showposts=1');

/* Now it loops through the results and displays the content.
*/

while ($my_query->have_posts()) : $my_query->the_post();

/* Then it displays the title as a working link with formatting to
* match the Twenty Ten template.
* Then we display the excerpt.
* Then we finish the loop with the endwhile statement
*/
?>

June 02 2010

20:42

Why Journalists Should Learn Computer Programming

Yes, journalists should learn how to program. No, not every journalist should learn it right now -- just those who want to stay in the industry for another ten years. More seriously, programming skills and knowledge enable us traditional journalists to tell better and more engaging stories.

Programming means going beyond learning some HTML. I mean real computer programming.

As a journalist, I'm full aware of the reasons why we don't learn programming -- and I'm guilty of using many of them. I initially thought there were good reasons not to take it up:

  • Learning to program is time-consuming. One look at the thick books full of arcane code and you remember why you became a journalist and not a mathematician or an engineer. Even if you are mathematically inclined, it's tough to find the time to learn all that stuff.
  • Your colleagues tell you you don't need it -- including the professional developers on staff. After all, it took them years of study and practice to become really good developers and web designers, just like it takes years for a journalist to become experienced and knowledgeable. (And, if you start trying to code, the pros on staff are the ones who'll have to clean up any mess you make.)
  • Learning the basics takes time, as does keeping your skills up to date. The tools change all the time. Should you still bother to learn ActionScript (Flash), or just go for HTML5? Are you sure you want to study PHP and not Python?
  • Why learn programming when there are so many free, ready-made tools online: Quizzes, polls, blogs, mind maps, forums, chat tools, etc. You can even use things like Yahoo Pipes to build data mashups without needing any code.
  • When Megan Taylor wrote for MediaShift about the programmer-journalist, she asked around for the perfect skillset. One response nearly convinced me to never think about programming ever again: "Brian Boyer, a graduate of Medill's journalism for programmers master's track and now News Applications Editor at the Chicago Tribune, responded with this list: XHTML / CSS / JavaScript / jQuery / Python / Django / xml / regex / Postgres / PostGIS / QGIS."

Those are some of the reasons why I thought I could avoid learning programming. But I was so wrong.

Why Journalists Should Program

You've heard the reasons not to start coding. Now here's a list of reasons why you should:

  • Every year, the digital universe around us becomes deeper and more complex. Companies, governments, organizations and individuals are constantly putting more data online: Text, videos, audio files, animations, statistics, news reports, chatter on social networks...Can professional communicators such as journalists really do their job without learning how the digital world works?
  • Data are going mobile and are increasingly geo-located. As a result, they tell the stories of particular neighborhoods and streets and can be used to tell stories that matter in the lives of your community members.
  • People have less time, and that makes it harder to grab their attention. It's essential to look for new narrative structures. Programming enables you to get interactive and tell non-linear stories.

Jquerylogo copy.jpg

  • You don't have to build everything from scratch. Let's take JavaScript, which is used for creating dynamic websites. Tools such as jQuery, a cross-browser JavaScript library, enable people to create interactivity with less effort. Web application frameworks such as Ruby on Rails and Django support the development of dynamic sites and applications. So it can be easier than you thought.

A Way of Looking At the World

Maybe you're not yet convinced. Even though jQuery makes your life easier, you still need a decent knowledge of JavaScript, CSS and HTML. Django won't help you if you never practiced Python. All of this takes time, and maybe you'll never find enough of it to get good at all this stuff.

Still, we must try. The good news is that it doesn't matter if you become proficient at the latest language. What is important, however, is that you're able to comprehend the underpinnings of programming and interactivity -- to be able to look at the world with a coder's point of view.

I'm still just a beginner, but I feel that this perspective provides you with an acute awareness of data. You start looking for data structures, for ways to manipulate data (in a good sense) to make them work for your community.

When covering a story, you'll think in terms of data and interactivity from the very start and see how they can become part of the narrative. You'll see data everywhere -- from the kind that floats in the air thanks to augmented reality, to the more mundane version contained in endless streams of status updates. Rather than being intimidated by the enormous amount of data, you'll see opportunities -- new ways to bring news and information to the community.

You probably won't have time to actually do a lot of the programming and data structuring yourself. But now you're equipped to have a valuable and impactful conversation with your geek colleagues. A conversation that gets better results than ever before.

So, even though it's probably a bit late for me to attend the new joint Master of Science degree program in Computer Science and Journalism at Columbia University, I can still learn How to Think Like a Computer Scientist using the the free MIT OpenCourseWare, take part in the Journalists/Coders Ning network, and find help at Help.HacksHackers.Com).

And so can you.

******

Are you a journalist who has taken up programming? A programmer with advice for journalists? Please share your experiences and insights in the comments.

Roland Legrand is in charge of Internet and new media at Mediafin, the publisher of leading Belgian business newspapers De Tijd and L'Echo. He studied applied economics and philosophy. After a brief teaching experience, he became a financial journalist working for the Belgian wire service Belga and subsequently for Mediafin. He works in Brussels, and lives in Antwerp with his wife Liesbeth.

This is a summary. Visit our site for the full post ».

May 25 2010

01:37

Homepage auto-update on Word Press

Currently, I update all the teasers on our homepage by hand: http://www.chicagonewscoop.org/

Clearly this sucks and is unnecessary, but when I redesigned our home page I lost the code that grabbed the latest post in each category (up to the tag) and generated a teaser such as you see now.

Unfortunately, my php skills are too non-existent to bring that auto-update feature back.

Is there some way to fix this state of affairs?

Tags: wordpress php

November 04 2009

00:11

Creating a Flash Facebook application with the Facebook Actionscript API

It’s time to see how can we build a Flash Facebook application.

What we are going to do is a Flash movie to be embedded in a Facebook application, able to interact with the user by publishing notes and stories on the wall.

The first thing we need is the official Facebook Actionscript API. This library contains all we need to create a complete Facebook Flash application.

You can download the source code at this link, but before messing with AS3, let’s create the PHP part.

I suggest you to read the Developing a Facebook Application for absolute beginners posts from 1 to 5 if you don’t know how to create a basic Facebook application.

Then, take a look at the PHP code:

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
<style>
     <?php echo htmlentities(file_get_contents("style.css", true)); ?>
</style>
 
<script>
     function grant() {
         document.setLocation("http://apps.facebook.com/flash_demo/");
     }
</script>
 
<?php
 
require_once "facebook.php";
 
$appapikey = "xxxxxxx";
$appsecret = "yyyyyy";
 
$facebook = new Facebook($appapikey, $appsecret);
 
$user_id = $facebook->require_login();
 
$has_permission = $facebook->api_client->users_hasAppPermission("publish_stream");
 
if(!$has_permission){
 
?>
 
<div class = "allow">You won't be able to test the flash demo if you don't allow publish stream permission -
 
<fb:prompt-permission perms="publish_stream" next_fbjs="grant()"><strong>ALLOW PERMISSION</strong></fb:prompt-permission></div>
 
<?php } ?>
 
<fb:swf swfsrc="http://www.gamemummy.com/facebook/flash_demo/facebook_demo.swf" allowscriptaccess="always" bgcolor="#ffffff" flashvars="" width="500" height="400"/>

Notice at lines 1-3 the way you can import CSS style sheets. Don’t forget to use htmlentities on the imported file.

Then, at lines 5-9 I created a simple javascript function called grant that just redirects the browser to the application page. That is, basically it refreshes the page, and it will be called once the user will grant (or won’t grant) the permission to publish contents on his wall by submitting the permission form as you can see at line 30.

This is possible thanks to next_fbjs="grant()".

Another important thing in this script you should arleady know is the way I ask for publishing permission.

You can ask for permission inside the Flash movie itself but I found it easier to ask directly from Php. This way, you can even hide the Flash movie if the user does not grant permissions.

But the core of the script, the think you did not see in previous tutorials is the way I include the Flash movie at line 34 with the fb:swf tag.

You can find the official documentation at this page, and the most interesting thing is Facebook is passing some interesting parameters to the movie.

Let’s see the Actionscript now… I used the button component to create the buttons but this is not important… here it is the commented script:

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package {
	import flash.display.Sprite;
	import fl.controls.Button;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	// facebook rlibraries
	import com.facebook.Facebook;
	import com.facebook.utils.FacebookSessionUtil;
	import com.facebook.commands.notifications.*;
	import com.facebook.commands.stream.*;
	import com.facebook.net.FacebookCall;
 
	public class facebook_demo extends Sprite {
		var text_field:TextField = new TextField();
		var my_button:Button;
		var fbook:Facebook;
		// these are the api and secret keys you should be used to
		var api_key:String="xxxxxxxxxxxxxxx";
		var secret_key:String="yyyyyyyyyyyyyyyy";
		// starting a new facebook session
		var fb_session:FacebookSessionUtil=new FacebookSessionUtil(api_key,secret_key,loaderInfo);
		// in this object I will store all variables Facebook will pass to the movie
		var passed_vars:Object;
		// this variable will hold all facebook API calls
		var fbcall:FacebookCall;
		public function facebook_demo() {
			// just placing some buttons...
			place_buttons();
			// just creating a text field...
			create_text_field();
			// initializing the session
			fbook=fb_session.facebook;
			// this function will just print out all variables Facebook is passing to the movie
			get_vars();
		}
		// this is the core function, the one that will handle clicks on buttons and publising notes or stories according
		// to the button I am pressing
		function onclick(event:MouseEvent):void {
			// retrieving the user id (it's one of the variables passed by Facebook)
			var uid:Number=Number(passed_vars["fb_sig_user"]);
			switch (event.currentTarget.label) {
				case "Publish a note" :
					// publishing a note
					fbcall=new SendNotification([uid],"just sent a self-notification using <a href = \"http://apps.facebook.com/flash_demo/\">Facebook Flash Demo</a>","user_to_user");
					fbook.post(fbcall);
					break;
				case "Publish a story" :
					// publishing a story
					fbcall=new PublishPost("is using Facebook Flash Demo",{'href':'http://apps.facebook.com/flash_demo/','name':'Facebook Flash Demo','description':'that\'s it','caption':'this image was published by a Flash Movie','media':[{'type': 'image','src':  'http://www.gamemummy.com/facebook/flash_demo/api.jpg', 'href': 'http://apps.facebook.com/flash_demo/'}]},[{'href':'http://apps.facebook.com/flash_demo/','text':'Visit Facebook Flash Demo'}],uid.toString());
					fbook.post(fbcall);
			}
		}
		function create_text_field():void {
			addChild(text_field);
			text_field.width=500;
			text_field.height=320;
			text_field.x=10;
			text_field.y=10;
		}
		function get_vars():void {
			var varname:String;
			var varvalue:String;
			passed_vars=root.loaderInfo.parameters;
			text_field.text="DEFAULT VARS PASSED BY FACEBOOK:\n\n";
			for (varname in passed_vars) {
				varvalue=String(passed_vars[varname]);
				text_field.appendText(varname + ":\t" + varvalue + "\n");
			}
		}
		function place_buttons():void {
			var bnames:Array=new Array("Publish a note","Publish a story");
			for (var i:int=0; i<2; i++) {
				my_button=new Button();
				addChild(my_button);
				my_button.label=bnames[i];
				my_button.move(125+150*i, 350);
				my_button.addEventListener(MouseEvent.CLICK, onclick);
			}
		}
	}
}

The interesting thing of this script is the way you can send notifications (line 44) and publish posts (line 49)… I won’t talk about notifications because Facebook will deprecate this method in late November/early December 2009 , but I want you to look at the way I publish the post following the format explained at the official attachment docs.

You can test the application at this page and download the full source code, library included.

Next time, we’ll see how to add more functions.

Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.

Don't be the product, buy the product!

Schweinderl