Showing posts with label wordpress. Show all posts

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";
  }
?>