Showing posts with label Tutorial. Show all posts

wordpress Include jQuery in WordPress Theme

by in , 0

The following is the best way to go about it. Add the following to the theme's functions.php file:

if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11);
function my_jquery_enqueue() {
   wp_deregister_script('jquery');
   wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
   wp_enqueue_script('jquery');
}

Replace the URL with the location of what version of jQuery you want to use.

Reference URL

wordpress Include Any File From Your Theme

by in , 0

<?php include (TEMPLATEPATH . '/your-file.php'); ?>

wordpress If Page Is Parent or Child

by in , 0

There are built in conditional WordPress functions for testing for a page:

if ( is_page(2) ) {
  // stuff
}

Or for testing if a page is a child of a certain page:

if ( $post->post_parent == '2' ) {
  // stuff
}

But there is no built in function that combines these two things, which is a fairly common need. For example, loading a special CSS page for a whole "branch" of content. Like a "videos" page and all its children individual videos pages.

This function (add to functions.php file) creates new logical function to be used in this way:

function is_tree($pid) {      // $pid = The ID of the page we're looking for pages underneath
	global $post;         // load details about this page
	if(is_page()&&($post->post_parent==$pid||is_page($pid))) 
               return true;   // we're at the page or at a sub page
	else 
               return false;  // we're elsewhere
};

Usage

if (is_tree(2)) {
   // stuff
}

wordpress ID the Body Based on URL

by in , 0

<?php
	$url = explode('/',$_SERVER['REQUEST_URI']);
	$dir = $url[1] ? $url[1] : 'home';
?>

<body id="<?php echo $dir ?>">

This would turn http://domain.tld/blog/home into "blog" (the second level of the URL structure). If at the root, it will return "home".

Here is an alternate method:

<?php
       $page = $_SERVER['REQUEST_URI'];
       $page = str_replace("/","",$page);
       $page = str_replace(".php","",$page);
       $page = str_replace("?s=","",$page);
       $page = $page ? $page : 'index'
?>

This would turn http://domain.tld/blog/home into "domaintldbloghome", which is far more specific. It also will remove ".php" file extensions and the default WordPress search parameter.

More Secure Method

function curr_virtdir($echo=true){
        $url = explode('/',$_SERVER['REQUEST_URI']);
        $dir = $url[1] ? $url[1] : 'home'; // defaults to this if in the root
        $dir = htmlentities(trim(strip_tags($dir))); // prevent injection into the DOM through this function
        if ($echo) echo $dir;
        return echo $dir; // ie. curr_virtdir(false)
}
function get_curr_virtdir(){
        curr_virtdir(false);
}

Returns the "middle" directory value:

On http://css-tricks.com it would return "home"
On http://css-tricks.com/snippets it would return "snippets"
On http://css-tricks.com/forums/viewforum.php?f=6 it would return "forums"

The strip_tags() and htmlentities() functions prevent malicious code from being insterted into the URL and ran, e.g.

<body id="foo"><script>alert("Booo");</script>

Usage for IDing the body:

<body id="<?php curr_virtdir(); ?>">

Other usage:

<?php
  if ( get_curr_virtdir() == "store" ){
    echo "Welcome to our awesome store !";
  } elseif ( get_curr_virtdir() == "home" ){
    echo "Welcome home :-)";
  } else {
    echo "Welcome on some other page";
  }
?>

wordpress HTML5 Shim in functions.php

by in , 0

Might as well keep your header.php clean and insert the shim from the functions.php file.

// add ie conditional html5 shim to header
function add_ie_html5_shim () {
    echo '<!--[if lt IE 9]>';
    echo '<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>';
    echo '<![endif]-->';
}
add_action('wp_head', 'add_ie_html5_shim');

The shim is to enable HTML5 elements to be able to be styled through CSS in Internet Explorer versions less than 9.

wordpress Get The First Image From a Post

by in , 0

Let's say you wanted to use the post thumbnail feature of WordPress, but had a whole archive of posts that would take too much time to go through. For new posts, you can be specific and use the feature as intended. For old posts, you just want to use the first image it finds in the content for the thumbnail, or a default if none present.

Add this to functions.php or make a functionality plugin:

function catch_that_image() {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_img = $matches[1][0];

  if(empty($first_img)) {
    $first_img = "/path/to/default.png";
  }
  return $first_img;
}

To use it, use this code in the loop:

if ( get_the_post_thumbnail($post_id) != '' ) {

  echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
   the_post_thumbnail();
  echo '</a>';

} else {

 echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
 echo '<img src="';
 echo catch_that_image();
 echo '" alt="" />';
 echo '</a>';

}

I found that has_post_thumbnail wasn't as reliable as the logic above.

Reference URL

wordpress Get ID from Page Name

by in , 0

Add to functions.php file:

function get_ID_by_page_name($page_name) {
   global $wpdb;
   $page_name_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = '".$page_name."' AND post_type = 'page'");
   return $page_name_id;
}

Now you can use this function in templates when you need an ID of a specific post/page and all you have is the name.

wordpress Get Featured Image URL

by in , 0

Post thumbnails are pretty useful and pretty easy to use in WordPress. Simply add:

add_theme_support('post-thumbnails'); 

To a theme's functions.php file and you'll get a Featured Image module on the admin screen for posts which allows you to select one.

It is also very easy to output that image as an HTML <img>:

the_post_thumbnail();

But what if you just need the URL? Say, you're going to use it as a background-image on an element rather than a content image. Unfortunately there is no super easy/obvious function for that.

Within the loop, you'll have to do:

$thumb_id = get_post_thumbnail_id();
$thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true);
$thumb_url = $thumb_url_array[0];

Then $thumb_url will be that URL.

wordpress Get Content by ID

by in , 0

Apparently there is no succinct WordPress function for just returning the content of a particular page by the ID of that page. This is that.

function get_the_content_by_id($post_id) {
  $page_data = get_page($post_id);
  if ($page_data) {
    return $page_data->post_content;
  }
  else return false;
}

Reference URL

wordpress Find ID of Top-Most Parent Page

by in , 0

This will find what the ID is of the top-most parent Page, in a nested child page. For example, this page you are literally looking at is nested under

<?php

if ($post->post_parent)	{
	$ancestors=get_post_ancestors($post->ID);
	$root=count($ancestors)-1;
	$parent = $ancestors[$root];
} else {
	$parent = $post->ID;
}

?>

$parent will be the correct ID. For example, for use with wp_list_pages.

Source: CSSGlobe

wordpress Facebook “Like” Button for WordPress

by in , 0

Some very easy copy-and-paste code here to add to the template for blog posts to allow for Facebook "liking" of the article. Probably best in the single.php template underneath where it outputs the content of the post.

<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo rawurlencode(get_permalink()); ?>&amp;layout=standard&amp;show-faces=true&amp;width=450&amp;action=like&amp;font=arial&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="true" id="facebook-like"></iframe>

wordpress Enable All Possible Post Formats

by in , 0

For your functions.php file in the theme.

add_theme_support( 'post-formats', 
	array( 
		'aside', 
		'gallery',
		'link',
		'image',
		'quote',
		'status',
		'video',
		'audio',
		'chat'
	) 
);
add_post_type_support( 'post', 'post-formats' );
add_post_type_support( 'page', 'post-formats' );
// and other custom post types if you have them

Reference URL

wordpress Embed a Page inside a Page

by in , 0

<?php $recent = new WP_Query("page_id=**ID**"); while($recent->have_posts()) : $recent->the_post();?>
       <h3><?php the_title(); ?></h3>
       <?php the_content(); ?>
<?php endwhile; ?>

The above code can be used within the regular page loop. Replace **ID** with the ID of the page you wish to embed.

wordpress Dynamic Title Tag

by in , 0

<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>

Reference URL

wordpress Dump All Custom Fields

by in , 0

WordPress has a built in function, the_meta(), for outputting all custom fields. But this function is limited in that it doesn't always output all of them. For example, it misses custom fields added by plugins which begin with an _ underscore.

This bit of code uses an alternate function, get_post_custom() which will return all of them, and display all values. Good for debugging.

<h3>All Post Meta</h3>

<?php $getPostCustom=get_post_custom(); // Get all the data ?>

<?php
    foreach($getPostCustom as $name=>$value) {

        echo "<strong>".$name."</strong>"."  =>  ";

        foreach($value as $nameAr=>$valueAr) {
                echo "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                echo $nameAr."  =>  ";
                echo var_dump($valueAr);
        }

        echo "<br /><br />";

    }
?>

Reference URL

wordpress Display Post Divider In Between Posts

by in , 0

Right before the closing of the The Loop, insert this code:

<?php
if (($wp_query->current_post + 1) < ($wp_query->post_count)) {
   echo '<div class="post-item-divider">Post Divider</div>';
}
?>

This will create a <div> you can style as a post divider. The cool part being, it only gets inserted between two posts, skipping the last one. Thanks to Craig Maclean.

wordpress Display Image Next To Each Tag

by in , 0

<?php
$posttags = get_the_tags(); // Get articles tags
$home = get_bloginfo('url'); // Get homepage URL

// Check tagslug.png exists and display it
if ($posttags) {
 foreach($posttags as $tag) {
       $image = "http://cdn.css-tricks.com/images/tag-images/$tag->slug.png";

       if (file_exists("images/tag-images/$tag->slug.png")) {
         echo '<a href="' . $home . '/tag/' . $tag->slug . '" /><img title="' . $tag->name . '" alt="' . $tag->name . '" src="' . $image . '" /></a>';

       // If no image found, output something else, possibly nothing.
       } else {
         echo '<p>Not found</p>';
       }
  }
}
?>

This code belongs inside the loop. It will look in a specific directory for any images that match the slugs of article tags, display them and link them to the relevant tag archive.

wordpress Display Author Info

by in , 0

The image that shows for the author comes from the email address set for that user which goes to a corresponding Gravatar. The display name and bio come from the User settings area in the Admin.

<div class="author-box">
   <div class="author-pic"><?php echo get_avatar( get_the_author_email(), '80' ); ?></div>
   <div class="author-name"><?php the_author_meta( "display_name" ); ?></div>
   <div class="author-bio"><?php the_author_meta( "user_description" ); ?></div>
</div>

That should be all the CSS hooks you need to style up the area however you want. Note: some of these functions are WordPress 2.8 and newer only.

Array Display a Tag Cloud

by in , 0

<?php wp_tag_cloud( array(

    'smallest' => 8,          // font size for the least used tag
    'largest'  => 22,         // font size for the most used tag
    'unit'     => 'px',       // font sizing choice (pt, em, px, etc)
    'number'   => 45,         // maximum number of tags to show
    'format'   => 'flat',     // flat, list, or array. flat = spaces between; list = in li tags; array = does not echo results, returns array
    'orderby'  => 'name',     // name = alphabetical by name; count = by popularity
    'order'    => 'ASC',      // starting from A, or starting from highest count
    'exclude'  => 12,         // ID's of tags to exclude, displays all except these
    'include'  => 13,         // ID's of tags to include, displays none except these
    'link'     => 'view',     // view = links to tag view; edit = link to edit tag
    'taxonomy' => 'post_tag', // post_tag, link_category, category - create tag clouds of any of these things
    'echo'     => true        // set to false to return an array, not echo it

) ); ?>

The default sizing, if none supplied, for this function is "pt" which is a bit unusual and often unreliable so make sure you change that parameter to how you size fonts normally on your site.

Less Weird Font Sizing

Tag clouds accomplish their varied font sizes by applying inline styling to each tag. The resulting font sizes can be really weird like style='font-size:29.3947354754px;'. Mike Summers proposes this solution:

<div id="tagCloud">
	<ul>
		<?php
			$arr = wp_tag_cloud(array(
				'smallest'             => 8,                      // font size for the least used tag
				'largest'                => 40,                    // font size for the most used tag
				'unit'                      => 'px',                 // font sizing choice (pt, em, px, etc)
				'number'              => 200,                 // maximum number of tags to show
				'format'                => 'array',            // flat, list, or array. flat = spaces between; list = in li tags; array = does not echo results, returns array
				'separator'          => '',                      //
				'orderby'              => 'name',           // name = alphabetical by name; count = by popularity
				'order'                   => 'RAND',          // starting from A, or starting from highest count
				'exclude'              => '',                      // ID's of tags to exclude, displays all except these
				'include'               => '',                      // ID's of tags to include, displays none except these
				'link'                       => 'view',             // view = links to tag view; edit = link to edit tag
				'taxonomy'         => 'post_tag',    // post_tag, link_category, category - create tag clouds of any of these things
				'echo'                    => true                 // set to false to return an array, not echo it
			));
			foreach ($arr as $value) {
				$ptr1 = strpos($value,'font-size:');
				$ptr2 = strpos($value,'px');
				$px = round(substr($value,$ptr1+10,$ptr2-$ptr1-10));
				$value = substr($value, 0, $ptr1+10) . $px . substr($value, $ptr2);
				$ptr1 = strpos($value, "class=");
				$value = substr($value, 0, $ptr1+7) . 'color-' . $px . ' ' . substr($value, $ptr1+7);
				echo '<li>' . $value . '</li> ';
			}
		?>
	</ul>
</div>

The result turns this:

<a href='url' class='tag-link-66' title='6 topics' style='font-size:29.3947354754px;'>Tag Name</a>

into this:

<a href='url' class='color-29 tag-link-66' title='6 topics' style='font-size:29px;'>Tag Name</a>

Notice the added bonus that the links has a class name of "color-29" now that it didn't before. Now you have a hook to colorize tag names based on their size.

Reference URL

Array Disable Automatic Formatting Using a Shortcode

by in , 0

function my_formatter($content) {
       $new_content = '';
       $pattern_full = '{(\[raw\].*?\[/raw\])}is';
       $pattern_contents = '{\[raw\](.*?)\[/raw\]}is';
       $pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);

       foreach ($pieces as $piece) {
               if (preg_match($pattern_contents, $piece, $matches)) {
                       $new_content .= $matches[1];
               } else {
                       $new_content .= wptexturize(wpautop($piece));
               }
       }

       return $new_content;
}

remove_filter('the_content', 'wpautop');
remove_filter('the_content', 'wptexturize');

add_filter('the_content', 'my_formatter', 99);

This goes in the PHP in your functions.php file. Once done, you can use the [raw] shortcode in your posts: [raw]Unformatted code[/raw]

Reference URL