0% found this document useful (0 votes)
219 views

Digging Into Wordpress

The document provides information and code snippets about common WordPress template functions and tags for handling things like conditionally loading scripts and stylesheets, titles, sidebars, search forms, footers, and more. It discusses functions like get_header(), get_footer(), get_sidebar(), wp_head(), wp_footer(), and includes examples of how and when to use them.

Uploaded by

testdungpt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
219 views

Digging Into Wordpress

The document provides information and code snippets about common WordPress template functions and tags for handling things like conditionally loading scripts and stylesheets, titles, sidebars, search forms, footers, and more. It discusses functions like get_header(), get_footer(), get_sidebar(), wp_head(), wp_footer(), and includes examples of how and when to use them.

Uploaded by

testdungpt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

Function Exists?

When you deactivate a plugin, you run the risk of a PHP


function being present in your theme that doesn't exist.
Essentially a disaster that will surely wreck your theme.
Before calling plugin-specific functions in your theme, use a
conditional to ensure it exists:
<?php
if (function_exists('get_poll')) { get_poll(); }
?>
----------------------------------
Perfect title tags (header.php)
<title>
<?php if (function_exists('is_tag') && is_tag()) {
single_tag_title('Tag Archive for &quot;'); echo '&quot; - ';
} elseif (is_archive()) {
wp_title(''); echo ' Archive - ';
} elseif (is_search()) {
echo 'Search for &quot;'.wp_specialchars($s).'&quot; - ';
} elseif (!(is_404()) && (is_single()) || (is_page())) {
wp_title(''); echo ' - ';
} elseif (is_404()) {
echo 'Not Found - ';
}
if (is_home()) {
bloginfo('name'); echo ' - '; bloginfo('description');
} else {
bloginfo('name');
}
if ($paged > 1) {
echo ' - page '. $paged;
} ?>
</title>
The All-In-One SEO Plugin that we mentioned earlier can also be put in charge of
handling page titles. The advantage is that it keeps this area of the theme clea
ner
and does provide what is generally considered the best page title format for SEO
.
The disadvantage being that it isnt very customizable or nearly as configurable a
s
doing it yourself.
---------------------------------
You can load your own script on the page like this:
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/myscri
pt.js"></script>
<?php if (is_page_template('page-archives.php')) { ?>
<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/css/
archives.css" type="text/css" media="screen" />
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/
js/archives.js"></script>
<?php } ?>
That will take effect if you are using a special page template for your archives
that
is literally named page-archives.php. If instead you happen to know the ID of the
page (available in the Admin area, see note on next page), that could be written
like this:
<?php if (is_page("5")) { ?>
<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/css/
archives.css" type="text/css" media="screen" />
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/
js/archives.js"></script>
<?php } ?>
where 5 in the first line is the page ID. Feel free to use PHPs or operators
here to cover multiple pages.
Putting all of that together, our code looks something like this:
<?php wp_enqueue_script('jquery'); ?>
<?php wp_head(); ?>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/
myscript.js"></script>
<?php if (is_page("5")) { ?>
<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/css/
archives.css" type="text/css" media="screen" />
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/
js/archives.js"></script>
<?php } ?>
Hey! Whats up with that wp_head() thing? Glad you asked
--------------------------------------
To see for yourself what the query
string is, you can echo it to the web page by adding this little snippet directl
y before the loop:
<?php global $query_string; echo $query_string; ?>
If we were to place this snippet above our single.php loop at the Digging into
WordPress site, the following information would be displayed on any single page:
year=2011&monthnum=02&name=version-3-update
In plain English, that reads: The date is February 2011 and the post name is
Version 3 Update. Likewise, if we echo that $query_string variable from our
archive.php file, and then visit the JavaScript category archive, we see this:
posts_per_page=10&what_to_show=posts&orderby=date&order=DESC&category_name=javas
cript
In plain English: Show ten Posts from the Javascript category in descending chron
ological order.
--------------------------------------
Some Common Loop Only Functions
<?php the_title(); ?>
This function displays the title of the current Post. Remember that we are in a
loop,
so if that loop runs five times, this function will display five different items
, namely,
the title for each of our five posts.
Here is a number of common and highly useful inside-loop-only functions:
the_permalink() - displays the permalink URL for each post
the_ID() - displays the ID of each post
the_author() - displays the name of the author for each post
the_category() - displays the category/categories to which each post belongs
While you are inside the loop, you also have access to a bunch of preset variabl
es
that are populated after the_post() is executed. These variables exist in the ob
ject
$post. Much of this object data is used by functions that use it in more elabora
te
ways, but the $post object provides raw data that is sometimes incredibly useful.
$post->ID - returns the ID of post; useful for other functions that need an ID.
$post->post_content - the actual post content, including all markup; useful
when you need to process the content of a post before outputting it.
$post->post_modified - returns the datestamp of the last time the post was
updated.
$post->post_name - returns the slug of the post.
In addition to these, there are many more. See http://digwp.com/u/399 for refere
nce.
----------------------------------
Some Common Outside Loop Functions
Some functions are built to return more global and/or generic information that
doesnt have anything to do with any one particular Post. As such, they are meant
to be used in templates outside of the loop.
Here is a number of common and frequently used outside-loop-only functions:
wp_list_pages() - displays a list of links to your static pages
next_posts_link() - displays a link to older posts in archive views
wp_tag_cloud() - displays a tag cloud of all your tags
get_permalink() - returns the permalink of a post for use in PHP
--------------------------------
Global Custom Fields (page 66)
Add this to your functions.php file:
<?php add_action('admin_menu', 'add_gcf_interface');
function add_gcf_interface() {
add_options_page('Global Custom Fields', 'Global Custom Fields', '8', 'functions
',
'editglobalcustomfields');
}
function editglobalcustomfields() { ?>
<div class="wrap">
<h2>Global Custom Fields</h2>
<form method="post" action="options.php">
<?php wp_nonce_field('update-options') ?>
<p><strong>Amazon ID:</strong><br />
<input type="text" name="amazonid" size="45"
value="<?php echo get_option('amazonid'); ?>" />
</p>
<p><input type="submit" name="Submit" value="Update Options" /></p>
<input type="hidden" name="action" value="update" />
<input type="hidden" name="page_options" value="amazonid" />
</form>
</div>
<?php } ?>
You can now display this value anywhere in your theme with the get_option() temp
late tag:
<?php echo get_option('amazonid'); ?>
-------------------------------------
The Sidebar
Sidebars are such ubiquitous design elements that special functionality is built
right
into WordPress for handling them. In any of your theme files where you wish to
display a sidebar, simply place the following template tag where you would like
it to appear:
<?php get_sidebar(); ?>
That function will go get the file sidebar.php and place its content where this
function was called. Working with multiple sidebars?
<?php get_sidebar('secondary'); ?>
That function will retrieve the file called sidebar-secondary.php and load that.
Despite all this special functionality, sidebars are by no means required. Dont w
ant one? Dont need
one? No problem. Just dont put a sidebar.php file in your theme and dont call the
function.
-------------------------------------
The Search Form
It is very common for a WordPress theme to have a file called searchform.php. Th
is
is because the search form may be used in multiple theme files and in different
locations, so placing it in its own file helps to keep things modular. Just like
the
sidebar, which you can include at your leisure with the get_sidebar() function,
you
can include your searchform.php in any other template file by calling this funct
ion:
<?php get_search_form(); ?>
This function accepts no other parameters, but of course if you had a good reaso
n
to rename searchform.php or keep it anywhere other than the root directory of
your theme, you could just use the standard include code instead:
<?php include(TEMPLATEPATH . '/inc/special-search-form.php'); ?>
Where might you use this?
On the 404 page (404.php)
In the else part of The Loop
In the sidebar
----------------------------------
The Footer
Just like headers and sidebars, footers are one of those ubiquitous design eleme
nts.
They are so commonly used that WordPress again has a special template tag for
including them into your theme:
<?php get_footer(); ?>
This function will accept only one parameter, a string, which works like the sid
ebar
function. Used without a parameter it will fetch the footer.php file and insert
it.
When used with a parameter like so
<?php get_footer("mini"); ?>
<?php get_footer("mega"); ?>
the get_footer() template tag will retrieve the theme files footer-mini.php and
footer-mega.php, respectively.
The wp_footer() Hook
Remember the wp_head() hook? Well, the wp_footer() hook is exactly like that, on
ly
used down in the footer instead. It tells WordPress, the footer is right here. All
by itself, it doesnt do anything, its just a generic hook that can be used to whic
h
scripts and other functionality may be attached.
For example, it is fairly common practice to load HTML-dependent JavaScript file
s
from within the footer instead of the header. The location of the wp_footer() ho
ok
within your footer.php file will determine where the JavaScript is displayed in
the
source code. Thus, a good place for this hook is just before the closing <body>
tag.
<?php wp_footer(); ?></body>
&copy; <?php echo date("Y"); bloginfo('name'); ?>
-----------------------------
<?php get_header(); ?>
<?php get_sidebar(); ?>
<div id="main-content">
// Loop
</div>
<?php get_sidebar("secondary"); ?>
<?php get_footer(); ?>
<div id="sidebar">
<!-- place markup and template tags here for your first sidebar -->
</div>
<div id="main-content">
<!-- place markup and template tags here for your post loop -->
</div>
<div id="sidebar-secondary">
<!-- place markup and template tags here for your second sidebar -->
</div>
<div id="footer">
<!-- place markup and template tags here for your footer -->
</div>
#sidebar { width: 200px; float: left; }
#main-content { width: 500px; float: left; }
#sidebar-secondary { width: 200px; float: right; }
#footer { clear: both; }
---------------------------------
Create a new page template just for archives, something like archives.php
<?php /* Template Name: Archives */ ?>
<?php get_header(); ?>
<div id="content">
<h2><?php the_title(); ?></h2>
<div class="col">
<h3>Archives by Year:</h3>
<ul><?php wp_get_archives('type=yearly'); ?></ul>
<h3>Archives by Month:</h3>
<ul><?php wp_get_archives('type=monthly'); ?></ul>
<h3>Archives by Day:</h3>
<ul><?php wp_get_archives('type=daily'); ?></ul>
<h3>Archives by Category:</h3>
<ul><?php wp_list_categories('title_li='); ?></ul>
<h3>Archives by Author:</h3>
<ul><?php wp_list_authors(); ?></ul>
</div>
<div class="col">
<h3>All Pages:</h3>
<ul><?php wp_list_pages('title_li='); ?></ul>
<h3>Archives by Tag:</h3>
<?php wp_tag_cloud(); ?>
</div>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
-------------------------------
Tag Cloud
<?php wp_tag_cloud(array(
'smallest' => 10, // size of least used tag
'largest' => 18, // size of most used tag
'unit' => 'px', // unit for sizing
'orderby' => 'name', // alphabetical
'order' => 'ASC', // starting at A
'exclude' => 6 // ID of tag to exclude from list
)); ?>
-----------------------------
WITHOUT A PLUGIN: DISPLAY RECENT COMMENTS
functions.php
<?php // display recent comments
function dp_recent_comments($no_comments = 10, $comment_len = 35) {
global $wpdb;
$request = "SELECT * FROM $wpdb->comments";
$request .= " JOIN $wpdb->posts ON ID = comment_post_ID";
$request .= " WHERE comment_approved = '1' AND post_status = 'publish'
AND post_password =''";
$request .= " ORDER BY comment_date DESC LIMIT $no_comments";
$comments = $wpdb->get_results($request);
if ($comments) {
foreach ($comments as $comment) {
ob_start(); ?>
<li>
<a href="<?php echo get_permalink( $comment->comment_post_ID
) . '#comment-' . $comment->comment_ID; ?>">< ?php echo dp_get_author($comment);
?>:</a>
< ?php echo strip_tags(substr(apply_filters('get_comment_
text', $comment->comment_content), 0, $comment_len)); ?>
</li>
< ?php
ob_end_flush();
}
} else {
echo '<li>No Comments</li>';
}
}
function dp_get_author($comment) {
$author = "";
if ( empty($comment->comment_author) )
$author = 'Anonymous';
else
$author = $comment->comment_author;
return $author;
} ?>
To use this function, simply call it from anywhere in your theme:
<?php dp_recent_comments(6); ?>
--------------------------
Displaying Recent Posts
Lets do this again from easiest to hardest.
Widget - The easiest possible way to do this is through a widgetized sidebar.
Just like recent comments, there is a built-in Recent Posts widget which will
do the trick. Just drag it into your sidebar zone and save it.
Custom Function - We dont have to write a custom function this time, we
can just use the wp_get_archives function, which we already looked at a little.
A
simple function like this will display linked titles to recent posts:
<?php wp_get_archives('type=postbypost&limit=5'); ?>
Custom Loop - Finally we could go totally home-brew and just write a custom
loop to display recent posts. This offers by far the most control as we can do
anything inside this loop, including accessing the full content or custom fields
.
<?php // display recent posts
$home_brew = new WP_Query('showposts=10&orderby=date');
while($home_brew->have_posts()) : $home_brew->the_post();
// output custom stuff here! Post title, content, custom fields..
endwhile;
wp_reset_postdata();
?>
--------------------------
Listing Popular Posts
try the WordPress Popular Posts plugin
This plugin logs relevant data and then makes outputting a list of popular posts
as
trivial as using this template tag anywhere in your theme:
<?php if (function_exists('get_mostpopular')) get_mostpopular(); ?>
If you wanted to gauge popularity only based on the number of comments, you
could achieve this with your own database query (thanks to the Bin Blog for the
idea http://digwp.com/u/118 ):
<ul class="popular-posts">
<?php $popular_posts = $wpdb->get_results("SELECT id,post_title FROM
{$wpdb->prefix}posts ORDER BY comment_count DESC LIMIT 0,10");
foreach($popular_posts as $post) {
print "<li><a href='". get_permalink($post->id) ."'>".
$post->post_title."</a></li>\n";
} ?>
</ul>
------------------------------
Easy Shortcode Permalinks
When you are building a theme, and the circumstance comes up
where you need to create a link to a specific page hard-baked
right into the theme, there is a function you should be using.
Not great
<a href="/contact/">Contact</a>
Much better
<a href="<?php echo get_permalink(12); ?>">Contact</a>
That 12 would be the ID of the Post or Page. Why is this better?
If the slug ever changes, you are still cool.
If the site moves from a sub directory (like if you were
developing and then moving) to a top level domain or vice
versa, you are still cool.
Doing it this way is a permanent reference to that Post or
Page that will always be correct. This works great when we are
working within our theme files, but what about when we are
working within WordPress and actually writing Posts and Pages?
By default, we cant run PHP within the content of our Posts
and Pages*, so we cant use the get_permalink function. What
we can do, is create a shortcode with just about the
same functionality.
((* If you need to run PHP inside Post content, check out this
plugin: http://digwp.com/u/465))
function permalink_thingy($atts) {
extract(shortcode_atts(array(
'id' => 1,
'text' => "" // default value if none supplied
), $atts));
if ($text) {
$url = get_permalink($id);
return "<a href='$url'>$text</a>";
} else {
return get_permalink($id);
}
}
add_shortcode('permalink', 'permalink_thingy');
This shortcode can be used in two ways:
Basic
<a href="[permalink id=49]">Using without providing text</a>
Provide only the ID parameter and it only returns a URL. This
way you can use that URL however you want. For example, if
you needed to add a special class name to the link or something
(but only occasionally).
Providing text
[permalink id=49 text='providing text']
This way returns a fully formatted anchor link back, using the
text you pass.

You might also like