wordpress Remove Paragraph Tags From Around Images

by in , 0

In case you want to have <img> in your content but not have them get "Auto P'd" like WordPress likes to do.

example of problem:

blah blah blah

<img src="monkey.jpg">

blah blah blah

turns into:

<p>blah blah blah</p>

<p><img src="monkey.jpg"></p>

<p>blah blah blah</p>

We can fix it with this:

function filter_ptags_on_images($content){
   return preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
}

add_filter('the_content', 'filter_ptags_on_images');

For your functions.php file, or, see Reference URL for a plugin. With this in place, we get:

<p>blah blah blah</p>

<img src="monkey.jpg">

<p>blah blah blah</p>

... meaning things like floating the images will be much easier.

Reference URL

wordpress Remove Link to the WLW Manifest File

by in , 0

Kind of pointless to include this unless you actually use Windows Live Writer to write your posts. Put this in the theme's functions.php file:

remove_action( 'wp_head', 'wlwmanifest_link');

wordpress Remove LI Elements From Output of wp_nav_menu

by in , 0

You can remove or change the <ul> container that you get by default with wp_nav_menu (codex) through parameters, but you can't remove the <li> elements that wrap each menu item. This is how you can actually remove them:

$menuParameters = array(
  'container'       => false,
  'echo'            => false,
  'items_wrap'      => '%3$s',
  'depth'           => 0,
);

echo strip_tags(wp_nav_menu( $menuParameters ), '<a>' );

wordpress Remove Gallery Inline Styling

by in , 0

add_filter( 'use_default_gallery_style', '__return_false' );

Reference URL

wordpress Remove Admin Bar For Subscribers

by in , 0

You might want open registration on your WordPress site so that (for one small example) people can log in and leave comments on things without needing to type their name/url/email every time. But these users probably don't need to see the whole top admin bar as there likely isn't much use in it for them. Although do be sure to provide a link to edit their profile and log out.

This would be for your functions.php file or functionality plugin:

add_action('set_current_user', 'cc_hide_admin_bar');
function cc_hide_admin_bar() {
  if (!current_user_can('edit_posts')) {
    show_admin_bar(false);
  }
}

wordpress Recent Posts Function

by in , 0

Technique #1

This function is useful when you need to display content, excerpt, custom fields, or anything related to the post beyond it's link and title. If you just need a list of linked titles, see the next technique. Put the following function in functions.php

function recent_posts($no_posts = 10, $excerpts = true) {

   global $wpdb;

   $request = "SELECT ID, post_title, post_excerpt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type='post' ORDER BY post_date DESC LIMIT $no_posts";

   $posts = $wpdb->get_results($request);

   if($posts) {

               foreach ($posts as $posts) {
                       $post_title = stripslashes($posts->post_title);
                       $permalink = get_permalink($posts->ID);

                       $output .= '<li><h2><a href="' . $permalink . '" rel="bookmark" title="Permanent Link: ' . htmlspecialchars($post_title, ENT_COMPAT) . '">' . htmlspecialchars($post_title) . '</a></h2>';

                       if($excerpts) {
                               $output.= '<br />' . stripslashes($posts->post_excerpt);
                       }

                       $output .= '</li>';
               }

       } else {
               $output .= '<li>No posts found</li>';
       }

   echo $output;
}

Usage

After you've made the function. Put the following in the sidebar or wherever you like the recent posts to list..

<?php recent_posts(); ?>

You can give it 2 arguments, the first is the number of posts and the second is whether or not you want to display the excerpts. so recent_posts(2, false) will display the 2 most recent post titles.

Technique #2

<?php wp_get_archives( array(

    'type'            => 'postbypost',   // or daily, weekly, monthly, yearly
    'limit'           => 10,   // maximum number shown
    'format'          => 'html',   // or select (dropdown), link, or custom (then need to also pass before and after params for custom tags
    'show_post_count' => false,    // show number of posts per link
    'echo'            => 1     // display results or return array

) ); ?> 

Technique #3

More succinct version of #1, which also includes a more standardized query string.

<?php
   $recentposts = get_posts('numberposts=12&category=4');
   foreach ($recentposts as $post) :
       setup_postdata($post); ?>
       <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>

Reference URL

wordpress Prevent Search Bots from Indexing Search Results

by in , 0

In the <head> section of your header.php file:

<?php if(is_search()) { ?>
   <meta name="robots" content="noindex, nofollow" /> 
<?php }?>

wordpress Prevent CSS Caching

by in , 0

WordPress:

<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); echo '?' . filemtime( get_stylesheet_directory() . '/style.css'); ?>" type="text/css" media="screen" />

bbPress:

<link rel="stylesheet" href="<?php bb_stylesheet_uri(); echo '?' . filemtime( bb_get_active_theme_directory() . '/style.css'); ?>" type="text/css" media="screen" />

Adds stylesheet with time of last update. If the number changes the browser updates the CSS instead of using cached version. Easily amended to be none WP specific.

wordpress Paginate Custom Post Types

by in , 0

<?php 
  $temp = $wp_query; 
  $wp_query = null; 
  $wp_query = new WP_Query(); 
  $wp_query->query('showposts=6&post_type=news'.'&paged='.$paged); 

  while ($wp_query->have_posts()) : $wp_query->the_post(); 
?>

  <!-- LOOP: Usual Post Template Stuff Here-->

<?php endwhile; ?>

<nav>
    <?php previous_posts_link('&laquo; Newer') ?>
    <?php next_posts_link('Older &raquo;') ?>
</nav>

<?php 
  $wp_query = null; 
  $wp_query = $temp;  // Reset
?>

wordpress Output Excerpt Manually

by in , 0

There is always the_excerpt(), but that does some pretty specific stuff (e.g. adding paragraph tags, adding [...], not respect the more comment, use the saved excerpt...). Advanced Excerpt is pretty good at customizing that.

If you want to get real simple though:

<?php 
  $content = get_the_content(); 
  echo substr(strip_tags($content), 0, 130) . '...'; 
?>

wordpress Natural Sort Using Post meta_key

by in , 0

@@ -2033,6 +2033,7 @@

      if ( !empty($q['meta_key']) ) {
              $allowed_keys[] = $q['meta_key'];
              $allowed_keys[] = 'meta_value';
+             $allowed_keys[] = 'meta_value_num';
      }
      $q['orderby'] = urldecode($q['orderby']);
      $q['orderby'] = addslashes_gpc($q['orderby']);

@@ -2056,6 +2057,9 @@

      case 'meta_value':
              $orderby = "$wpdb->postmeta.meta_value";
              break;
+     case 'meta_value_num':
+             $orderby = "$wpdb->postmeta.meta_value+0";
+             break;
      default:
              $orderby = "$wpdb->posts.post_" . $orderby;
}

This is a direct edit to a core file: /wp-includes/query.php Note the plus signs in the above code indicate new lines to add.

Author Notes:

A client wanted me to setup a custom field called "Guide Rank" which allowed them to assign #1 - 20 for a list of Bars they were posting about.

After running the posts query I found that the meta_value was being treated as a string and as such the sort order was jumbled:

eg. 1, 10, 2, 3css-tricks.comC 7 , 8 , 9

To get WordPress/MySQL to use "Natural Sort Order" you just need to apply +0 to the field name and it'll be treated as a number (eg. meta_value+0).

So that existing behavior is not interrupted I've just added the new type 'meta_value_num'.

My query line now looks like:

$guide_posts = new WP_Query("cat=12&meta_key=guide_rank&orderby=meta_value_num&order=ASC&showposts=10");

Which returns: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

This is up for inclusion in the WordPress trunk - so hopefully once it gets applied there should be no need for manually editing the file.

wordpress Move WordPress Admin Bar to the Bottom

by in , 0

Pre WordPress 3.3 only. Either add this CSS to your CSS file, add all the code to your functions.php file, or make a quick little plugin.

function fb_move_admin_bar() {
    echo '
    <style type="text/css">
    body {
    margin-top: -28px;
    padding-bottom: 28px;
    }
    body.admin-bar #wphead {
       padding-top: 0;
    }
    body.admin-bar #footer {
       padding-bottom: 28px;
    }
    #wpadminbar {
        top: auto !important;
        bottom: 0;
    }
    #wpadminbar .quicklinks .menupop ul {
        bottom: 28px;
    }
    </style>';
}
// on backend area
add_action( 'admin_head', 'fb_move_admin_bar' );
// on frontend area
add_action( 'wp_head', 'fb_move_admin_bar' );

Reference URL

wordpress Make Archives.php Include Custom Post Types

by in , 0

Archives.php only shows content of type 'post', but you can alter it to include custom post types. Add this filter to your functions.php file:

function namespace_add_custom_types( $query ) {
  if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
    $query->set( 'post_type', array(
     'post', 'your-custom-post-type-here'
		));
	  return $query;
	}
}
add_filter( 'pre_get_posts', 'namespace_add_custom_types' );

wordpress Login/Logout and User Welcome

by in , 0

<div id="user-details">
<?php
   if (is_user_logged_in()) {
      $user = wp_get_current_user();
      echo ‘Welcome back <strong>’.$user->display_name.‘</strong> !’;
   } else { ?>
      Please <strong><?php wp_loginout(); ?></strong>
      or <a href="<?php echo get_option(’home’); ?>/wp-login.php?action=register"> <strong>Register</strong></a>
<?php } ?>
</div>

Uses WordPress functions and queries to pull user information, and to display the login/logout/register links.

wordpress List Posts, Highlight Current

by in , 0

WordPress lacks a wp_list_posts() function that might seem logical go with the robust and useful wp_list_pages() function. You can simulate it though, by using the get_posts() function and running your own loop through the results.

The parameters for get_posts() below are just examples, replace with your needs.

<ul>

    <?php
        $lastposts = get_posts('numberposts=5&orderby=rand&cat=-52');
        foreach($lastposts as $post) :
        setup_postdata($post); ?>

        <li<?php if ( $post->ID == $wp_query->post->ID ) { echo ' class="current"'; } else {} ?>>
            
            <a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
            
        </li>

    <?php endforeach; ?>

</ul>

wp_list_pages() also has the feature of adding a class name of "current_page_item" to the list element when that page is the active one. Notice the opening list tag above, which replicates that functionality by seeing if the ID from the current query matches the ID from the current iteration of the loop.

wordpress Insert Images within Figure Element from Media Uploader

by in , 0

For your functions.php file or a functionality plugin:

function html5_insert_image($html, $id, $caption, $title, $align, $url) {
  $html5 = "<figure id='post-$id media-$id' class='align-$align'>";
  $html5 .= "<img src='$url' alt='$title' />";
  if ($caption) {
    $html5 .= "<figcaption>$caption</figcaption>";
  }
  $html5 .= "</figure>";
  return $html5;
}
add_filter( 'image_send_to_editor', 'html5_insert_image', 10, 9 );

It also takes what you enter as a caption and inserts it within the <figure> tag as a <figcaption>. Example inserted code:

<figure id='post-18838 media-18838' class='align-none'>
  <img src='http://youresite.com/wp-content/uploads/2012/10/image.png' alt='Title of image'>
  <figcaption>Caption for image</figcaption>
</figure>

wordpress Insert Images with Figure/Figcaption

by in , 0

For a simple plugin or functions.php file:

function html5_insert_image($html, $id, $caption, $title, $align, $url) {
  $html5 = "<figure id='post-$id media-$id' class='align-$align'>";
  $html5 .= "<img src='$url' alt='$title' />";
  if ($caption) {
    $html5 .= "<figcaption>$caption</figcaption>";
  }
  $html5 .= "</figure>";
  return $html5;
}
add_filter( 'image_send_to_editor', 'html5_insert_image', 10, 9 );

Reference URL

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

Array Disable Automatic Formatting

by in , 0

Add to functions.php file

remove_filter('the_content', 'wptexturize');
remove_filter('the_excerpt', 'wptexturize');
remove_filter('comment_text', 'wptexturize');
remove_filter('the_title', 'wptexturize');

the wptexturize function is responsible for lots of automatic alterations to text stored in WordPress like automatic elipses (...), em and en dashes, typographers quotes, etc.

Array Detect Gists and Embed Them

by in , 0

Just post a link to a GitHub Gist and it will be nicely embedded. Or use the format this snippet provides and create the shortcode yourself. For your functions.php file:

<?php
// [gist id="ID" file="FILE"]
function gist_shortcode($atts) {
  return sprintf(
    '<script src="https://gist.github.com/%s.js%s"></script>', 
    $atts['id'], 
    $atts['file'] ? '?file=' . $atts['file'] : ''
  );
} add_shortcode('gist','gist_shortcode');

// Remove this function if you don't want autoreplace gist links to shortcodes
function gist_shortcode_filter($content) {
  return preg_replace('/https:\/\/gist.github.com\/([\d]+)[\.js\?]*[\#]*file[=|_]+([\w\.]+)(?![^<]*<\/a>)/i', '[gist id="${1}" file="${2}"]', $content );
} add_filter( 'the_content', 'gist_shortcode_filter', 9);
?>

Any of these formats will work:

https://gist.github.com/1147076 https://gist.github.com/1147076#file_annotated.js https://gist.github.com/1147076.js?file=annotated.js [gist id=1147076] [gist id=1147076 file=annotated.js]

Reference URL

Array Customize Login Page

by in , 0

You know, the one typically at yoursite.com/wp-login.php. These are things you would put in the active theme's functions.php file.

Change the Logo

Is the WordPress logo by default, this changes the file path of that image. Change file path and file name to your own needs.

function custom_login_logo() {
	echo '<style type="text/css">h1 a { background: url('.get_bloginfo('template_directory').'http://cdn.css-tricks.com/images/logo-login.gif) 50% 50% no-repeat !important; }</style>';
}
add_action('login_head', 'custom_login_logo');

Change the URL

... of where clicking that logo goes. By default it goes to WordPress.org, this will change it to your own homepage.

function change_wp_login_url() {
	return bloginfo('url');
}
add_filter('login_headerurl', 'change_wp_login_url');

Change the Title

That is, change the title attribute of the image you just replaced. This changes it to the name of your blog in the settings.

function change_wp_login_title() {
	return get_option('blogname');
}
add_filter('login_headertitle', 'change_wp_login_title');

Array Customize Comments Markup

by in , 0

In a typical WordPress theme you output the entire list of comments for a Post/Page by using the function wp_list_comments(). This doesn't offer much by the way of customizing what HTML markup gets generated for that comment list. To write your own markup for the comment list, you can use a callback function as a parameter in wp_list_comments(), so it's just as nicely abstracted.

In functions.php

<?php
function my_custom_comments($comment, $args, $depth) {
   $GLOBALS['comment'] = $comment; ?>
   <li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
   <?php if ($comment->comment_approved == '0') : ?>
      <em><?php _e('Your comment is awaiting moderation.') ?></em>
   <?php endif; ?>

   // Comments markup code here, e.g. functions like comment_text(); 

}
?>

In comments.php

<?php 
   wp_list_comments("callback=my_custom_comments"); 
?>

Tutorial Change Avatar Size

by in , 0

The wp_list_comments function has a parameter to change the default (48px) size to anywhere between 0 and 80px.

wp_list_comments('avatar_size=80');

Tutorial Bloginfo Shortcode

by in , 0

The bloginfo() function in WordPress gives you access to lots of useful information about your site. See the complete list. To access all these values from inside Page/Post content itself, we can make a shortcode to return the values. Add this to your functions.php file in your theme:

function digwp_bloginfo_shortcode( $atts ) {
   extract(shortcode_atts(array(
       'key' => '',
   ), $atts));
   return get_bloginfo($key);
}
add_shortcode('bloginfo', 'digwp_bloginfo_shortcode');

Now you can output any of the values by calling that shortcode with "key". For example, the name of your site:

[bloginfo key='name']

Or directly to images in your theme folder:

<img src="[bloginfo key='template_url']/images/logo.jpg" alt="[bloginfo key='name'] logo" />

Reference URL

Tutorial Base Threaded Comments Styling

by in , 0

ol.commentlist { list-style:none; margin:0 0 1em; padding:0; text-indent:0; }
ol.commentlist li { }
ol.commentlist li.alt { }
ol.commentlist li.bypostauthor {}
ol.commentlist li.byuser {}
ol.commentlist li.comment-author-admin {}
ol.commentlist li.comment { border-bottom:1px dotted #666; padding:1em; }
ol.commentlist li.comment div.comment-author {}
ol.commentlist li.comment div.vcard { font:normal 16px georgia,times,serif; }
ol.commentlist li.comment div.vcard cite.fn { font-style:normal; }
ol.commentlist li.comment div.vcard cite.fn a.url {}
ol.commentlist li.comment div.vcard img.avatar { border:5px solid #ccc; float:right; margin:0 0 1em 1em; }
ol.commentlist li.comment div.vcard img.avatar-32 {}
ol.commentlist li.comment div.vcard img.photo {}
ol.commentlist li.comment div.vcard span.says {}
ol.commentlist li.comment div.commentmetadata {}
ol.commentlist li.comment div.comment-meta { font-size:9px; }
ol.commentlist li.comment div.comment-meta a { color:#ccc; }
ol.commentlist li.comment p { font-size:11px; margin:0 0 1em; }
ol.commentlist li.comment ul { font-size:11px; list-style:square; margin:0 0 1em 2em; }
ol.commentlist li.comment div.reply { font-size:11px; }
ol.commentlist li.comment div.reply a { font-weight:bold; }
ol.commentlist li.comment ul.children { list-style:none; margin:1em 0 0; text-indent:0; }
ol.commentlist li.comment ul.children li {}
ol.commentlist li.comment ul.children li.alt {}
ol.commentlist li.comment ul.children li.bypostauthor {}
ol.commentlist li.comment ul.children li.byuser {}
ol.commentlist li.comment ul.children li.comment {}
ol.commentlist li.comment ul.children li.comment-author-admin {}
ol.commentlist li.comment ul.children li.depth-2 { border-left:5px solid #555; margin:0 0 .25em .25em; }
ol.commentlist li.comment ul.children li.depth-3 { border-left:5px solid #999; margin:0 0 .25em .25em; }
ol.commentlist li.comment ul.children li.depth-4 { border-left:5px solid #bbb; margin:0 0 .25em .25em; }
ol.commentlist li.comment ul.children li.depth-5 {}
ol.commentlist li.comment ul.children li.odd {}
ol.commentlist li.even { background:#fff; }
ol.commentlist li.odd { background:#f6f6f6; }
ol.commentlist li.parent { border-left:5px solid #111; }
ol.commentlist li.thread-alt { }
ol.commentlist li.thread-even {}
ol.commentlist li.thread-odd {}

Reference URL

Tutorial Automatic Social Media Links

by in , 0

This would go inside the loop, probably underneath the_content(), probably in your single.php file.

// bookmark on Delicious
<a rel="nofollow" href="http://delicious.com/post?url=<?php the_permalink(); ?>&amp;title=<?php echo urlencode(get_the_title($id)); ?>" title="Bookmark this post at Delicious">Bookmark at Delicious</a>

// submit to Digg
<a rel="nofollow" href="http://digg.com/submit?phase=2&amp;url=<?php the_permalink(); ?>" title="Submit this post to Digg">Digg this!</a>

// tweet on Twitter
<a rel="nofollow" href="http://twitter.com/home?status=<?php echo urlencode("Currently reading: "); ?><?php the_permalink(); ?>" title="Share this article with your Twitter followers">Tweet this!</a>

// submit to StumbleUpon
<a rel="nofollow" href="http://www.stumbleupon.com/submit?url=<?php the_permalink(); ?>&amp;title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post at StumbleUpon">Stumble this!</a>

// share on Facebook
<a rel="nofollow" href="http://www.facebook.com/sharer.php?u=<?php the_permalink();?>&amp;t=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Facebook">Share on Facebook</a>

// submit to Blinklist
<a rel="nofollow" href="http://blinklist.com/index.php?Action=Blink/addblink.php&amp;url=<?php the_permalink(); ?>&amp;Title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Blinklist" >Blink This!</a>

// store on Furl
<a rel="nofollow" href="http://furl.net/storeIt.jsp?t=<?php echo urlencode(get_the_title($id)); ?>&amp;u=<?php the_permalink(); ?>" title="Share this post on Furl">Furl This!</a>

// submit to Reddit
<a rel="nofollow" href="http://reddit.com/submit?url=<?php the_permalink(); ?>&amp;title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Reddit">Share on Reddit</a>

Reference URL

Tutorial Apply Custom CSS to Admin Area

by in , 0

Add to the functions.php file:

add_action('admin_head', 'my_custom_fonts');

function my_custom_fonts() {
  echo '<style>
    body, td, textarea, input, select {
      font-family: "Lucida Grande";
      font-size: 12px;
    } 
  </style>';
}

Tutorial Allow SVG through WordPress Media Uploader

by in , 0

For your functions.php file or a functionality plugin:

function cc_mime_types( $mimes ){
	$mimes['svg'] = 'image/svg+xml';
	return $mimes;
}
add_filter( 'upload_mimes', 'cc_mime_types' );

Without this, SVG files will be rejected when attempting to upload them through the media uploader.

Tutorial Admin Panel Link Only For Admins

by in , 0

<?php if (current_user_can("manage_options")) : ?>
       <a href="<?php echo bloginfo("siteurl") ?>/wp-admin/">Admin</a>
<?php endif; ?>

If a user is logged in and they are an Admin of the site (not just an subscriber or author), then display a link to get them to the WordPress Admin area. Otherwise, display nothing.

More specific than the regular log in / log out function, which will show for everyone:

<?php wp_loginout(); ?>

Tutorial Add/remove contact info fields

by in , 0

User profiles in WordPress by default have these fields for Contact Info by default: E-mail, Website, AIM, Yahoo IM, Jabber / Google Talk. You can remove those and add new ones as you wish, like in this example code for your functions.php file in your theme:

function new_contactmethods( $contactmethods ) {
   $contactmethods['twitter'] = 'Twitter'; // Add Twitter
   $contactmethods['facebook'] = 'Facebook'; // Add Facebook
   unset($contactmethods['yim']); // Remove YIM
   unset($contactmethods['aim']); // Remove AIM
   unset($contactmethods['jabber']); // Remove Jabber

   return $contactmethods;
}

To display that publicly, you could:

$user_id = 1;
$key = 'twitter';
$single = true;

$user_twitter = get_user_meta( $user_id, $key, $single); 

echo $user_twitter; 

Reference URL

Tutorial Add class to links generated by next_posts_link and previous_posts_link

by in , 0

These two functions create anchor links, and you can customize a lot of it, but it's impossible to add a class through just using their parameters alone. Gotta add a function to functions.php:

add_filter('next_posts_link_attributes', 'posts_link_attributes');
add_filter('previous_posts_link_attributes', 'posts_link_attributes');

function posts_link_attributes() {
    return 'class="styled-button"';
}

Reference URL