Arquivo da tag: wordpress hacks

WORDPRESS ARTIGOS POPULARES NA BARRA LATERAL

ARTIGOS POPULARES NA BARRA LATERAL. Criar um widget para mostrar os artigos populares do seu blog na sua barra lateral sem usar plugins é extremamente fácil. Copie e cole o seguinte código para dentro do seu ficheiro sidebar.php. Se precisar de alterar o número de artigos mostrados, altere o valor 5 que se encontra no final da linha 3 de código.

wordpress-code

Artigos Populares

    < ?php $result = $wpdb->get_results("SELECT comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 5");
    foreach ($result as $post) {
    setup_postdata($post);
    $postid = $post->ID;
    $title = $post->post_title;
    $commentcount = $post->comment_count;
    if ($commentcount != 0) { ?>


  • < ?php echo $title ?>
    {< ?php echo $commentcount ?>}
  • < ?php } } ?>

CRIAR META DESCRIÇÃO DE ARTIGOS AUTOMATICAMENTE

CRIAR META DESCRIÇÃO DE ARTIGOS AUTOMATICAMENTE. Adicione o seguinte código ao functions.php do seu blog, ele irá criar automaticamente a meta descrição dos seus artigos, a partir da função the_content. Tenha a certeza de que cola este código no ficheiro header.php do seu template WordPress ou o truque não irá funcionar corretamente

function create_meta_desc() {
global $post;
if (!is_single()) { return; }
$meta = strip_tags($post->post_content);
$meta = strip_shortcodes($post->post_content);
$meta = str_replace(array("\n", "\r", "\t"), ' ', $meta);
$meta = substr($meta, 0, 125);
echo "";
}
add_action('wp_head', 'create_meta_desc');

 META DESCRIÇÃO DE ARTIGOS AUTOMATICAMENTE

META DESCRIÇÃO DE ARTIGOS AUTOMATICAMENTE

Limitar numero de post por página

Limitar numero de post por página. Adicione o código no functions.php do tema para determinar o número de artigos por página. Este código pode ser configurado para para tags e outras páginas wordpress.

function.php:
Mude o número de post por categorias de 5 para o número que você deseja.

add_filter('pre_get_posts', 'limit_category_posts');
function limit_category_posts($query){
if ($query->is_category) {
$query->set('posts_per_page', 5);
}
return $query;
}

function.php:
Mude o número de post por arquivos de 5 para o número que você deseja.

add_filter('pre_get_posts', 'limit_archive_posts');
function limit_archive_posts($query){
if ($query->is_archive) {
$query->set('posts_per_page', 5);
}
return $query;
}

function.php:
Mude o número de post por categorias específicas, ou seja, aqui o exemplo as categorias são livros, id 77 etc, de 5 para o número que você deseja.

add_filter('pre_get_posts', 'per_category_basis');
function per_category_basis($query){
if ($query->is_category) {
// category named 'livos' show 12 posts
if (is_category('livros'){
$query->set('posts_per_page', 12);
}
// category With ID = 77 show only 5 posts
if (is_category('77'){
$query->set('posts_per_page', 5);
}
}
return $query;
}

Adicione direto no loop da página category.php, tag.php, author.php etc. O código vai determinar o número de artigos a ser exibidos diferentes daquele defindo no painel de configuração do wordpress.

category.php, tag.php etc:


global $query_string;
query_posts("{$query_string}&posts_per_page=5");

Códigos WordPress para Arquivos e Diretórios

Códigos WordPress para Arquivos e Diretórios. Alguns códigos que ajudam a melhorar a aparência do tema wordpress. Os códigos a seguir melhoram o desempenho do site bem como facilitam a escrita da semântica.

Códigos WordPress para Arquivos e Diretórios

Plugins

plugins_url()
plugin_dir_url()
plugin_dir_path()
plugin_basename()

Themes

get_template_directory_uri()
get_stylesheet_directory_uri()
get_stylesheet_uri()
get_theme_root_uri()
get_theme_root()
get_theme_roots()
get_stylesheet_directory()
get_template_directory()

Site Home

home_url()
get_home_path()

WordPress

admin_url()
site_url()
content_url()
includes_url()
wp_upload_dir()

Multisite

get_admin_url()
get_home_url()
get_site_url()
network_admin_url()
network_site_url()
network_home_url()

Constants

WP_CONTENT_DIR // no trailing slash, full paths only
WP_CONTENT_URL // full url
WP_PLUGIN_DIR // full path, no trailing slash
WP_PLUGIN_URL // full url, no trailing slash

WordPress Directories:
home_url() Home URL http://www.example.com
site_url() Site directory URL http://www.example.com or http://www.example.com/wordpress
admin_url() Admin directory URL http://www.example.com/wp-admin
includes_url() Includes directory URL http://www.example.com/wp-includes
content_url() Content directory URL http://www.example.com/wp-content
plugins_url() Plugins directory URL http://www.example.com/wp-content/plugins
theme_url() Themes directory URL (#18302) http://www.example.com/wp-content/themes
wp_upload_dir() Upload directory URL (returns an array) http://www.example.com/wp-content/uploads
Categories:

COMO MUDAR O TEXTO DE RODAPÉ DA DASHBOARD DO WORDPRESS

MUDAR O TEXTO DE RODAPÉ DA DASHBOARD. Se desejar alterar o texto que aparece no rodapé da dashboard do WordPress, isso também é fácil. Copie e cole o seguinte código para dentro do ficheiro functions.php do seu template, e altere o texto padrão que aparece na linha 2 do código. Continue lendo

COMO MUDAR AS CORES DA DASHBOARD DO WORDPRESS

MUDAR AS CORES DA DASHBOARD. Se gostaria de alterar as cores da dashboard do WordPress sem ter de editar os ficheiros nativos do WordPress, você vai curtir este truque. O código seguinte tem uma alteração de cor de cinza para azul, mas você pode modificá-lo entre a tag style com as cores que bem desejar. Continue lendo

COMO MUDAR O TEXTO “DIGITE O TÍTULO AQUI” DO WORDPRESS

MUDAR O TEXTO “DIGITE O TÍTULO AQUI”. Se por alguma razão você precisar de mudar o texto “Digite o título aqui” que se encontra no editor de artigos do WordPress, e colocar no seu lugar um outro texto qualquer, você apenas precisa copiar e colar o seguinte código no ficheiro functions.php Continue lendo

COMO REMOVER ITEMS DA BARRA DE ADMIN DO WORDPRESS

REMOVER ITEMS DA BARRA DE ADMIN. Se pretende prevenir que os seus clientes acessem determinados menus por meio da barra de admin do WordPress, como as seções de “Plugins” ou “Opções”, basta você copiar e colar o seguinte código no ficheiro functions.php do seu template, seleccionando os items que você deseja remover. Continue lendo

WordPress Chamando corretamente as funções no theme

Muitos programadores desenvolvem excelentes plugins que exigem configuração do tema wordpress, na maioria das vezes as funções são chamadas usando o código php diretamente, nada demais, funciona perfeitamente, contudo se por ventura o plugin for desabilitado ou a função no escrita no function.php for removido todo o blog fica comprometido.

Não declare a funcão desta maneira: < ?php função(); ?>

Use a sintaxe abaixo para declarar corretamente a função e não ter problemas.

< ?php if (function_exists('função')) { função(); } ?>

Personalizando as Tags Cloud WordPress

Copy this code into /wp-content/themes/yourtheme/functions.php
Run < ?php echo get_my_tags(); ?> wherever you want a tag cloud
Make sure the tag archive URL on line 40 points to the right place
Optionally change $smallest and $largest (on lines 3 & 4) to the preferred pixel size of your smallest and largest tags

function get_my_tags()
{
$smallest = 14;
$largest = 26;
$tags = get_tags();
$counts = array();

foreach($tags as $key => $tag)
{
if($tag->count < 2) { unset($tags[$key]); } }foreach ( (array) $tags as $key => $tag )
{
$counts[ $key ] = $tag->count;
}

$min_count = min($counts);
$spread = max($counts) – $min_count;

if ( $spread < = 0 ) { $spread = 1; }$font_spread = $largest - $smallest; if ( $font_spread < 0 ) { $font_spread = 1; }$font_step = $font_spread / $spread;$html = '

‘;
foreach($tags as $tag)
{
$html .= ‘< a href="/tags/' . $tag->slug . ‘/” style=”font-size:’ . round($smallest + ($tag->count – $min_count) * $font_step) . ‘px”>’ . $tag->name . ‘< /a> ‘;
}
$html .= ”;
return $html;
}

Automatically provide ShortURL for your WordPress blog posts

Automatically provide shorturls for your WordPress blog posts

Are you on Twitter? I am. This service make an intensive use of shorturls in order to reduce the size of urls. Why not provide automatically provide a shorturl to your readers so they can use it on Tweeter?

To achieve this recipe, simply open your functions.php file and paste the following code

function getsUrl($url) {
$surl = file_get_contents(“http://s.jar.io/api.php?url=”.$url);
return $surl;
}

On your single.php file, paste the following within the loop:

< ?php $turl = getsUrl(get_permalink($post->ID));
echo ‘ShortURL: < a href="'.$turl.'">‘.$turl.’< /a>‘
?>

WordPress Search Hacks

WordPress Search Hacks

Display the number of results in WordPress search

WordPress users know it: Search is definitely one of WordPress weak point. Today, let’s see how to get the number of results the search returned, and display it (proudly!) on our blog.

Open your search template file, search.php. In it, search for the following:

Search Results

Now replace this with:

Search Results for < ?php /* Search Count */ $allsearch = &new WP_Query("s=$s&showposts=-1"); $key = wp_specialchars($s, 1); $count = $allsearch->post_count; _e(”); _e(‘‘); echo $key; _e(‘‘); _e(‘ — ‘); echo $count . ‘ ‘; _e(‘articles’); wp_reset_query(); ?>

That’s all, you’re done!
Highlight the Search Terms in Results

When you search on Google or any other major search engine, the words you searched for are highlighted in the results to make it easier for you to scan. We can do the same with your search results page.

In search.php, search for the following:

< ?php the_title(); ?>

This is the code for showing the title of each of the results. In the default theme, it will be wrapped up in a line like this:

” rel=”bookmark” title=”Permanent Link to < ?php the_title_attribute(); ?>“>< ?php the_title(); ?>

Now, replace the part with:

< ?php echo $title; ?>

Finally, before this line, paste the following:

< ?php $title = get_the_title(); $keys= explode(" ",$s); $title = preg_replace('/('.implode('|', $keys) .')/iu', '’, $title); ?>

source

Make your WordPress Search Results Unlimited

Sometimes you may not want your search results to be limited by the confines of the standard WordPress Loop. This is a quick code hack to allow a search to return unlimited results, altering the standard WordPress Loop by using a custom query. You can do this in a few different ways. If you have a search template, in search.php you can simple add the following line of code above your Loop.

Find:

< ?php if (have_posts()) : ?>
< ?php while (have_posts()) : the_post(); ?>

Add:

< ?php $posts=query_posts($query_string . '&posts_per_page=-1'); ?>
< ?php if (have_posts()) : ?>
< ?php while (have_posts()) : the_post(); ?>

WordPress Tags Categories and Archives Hacks

WordPress Tags Categories and Archives Hacks

Find WordPress category ID

Some themes requires that you fill a form field with a category ID. It may be easy to find a category ID if you’re an advanced WordPres user, but what about beginners? Here’s a very simple manner to find any category ID.

Once you’re logged in your WordPress dashboard, go to Manage and then in Categories.
Simply put your mouse cursor on the “edit” link related to the category you want to know the ID and look on your browser’s status bar: As you can see on the screenshot below, 1 is the id of the category.

Display Certain Categories in a Menu

In many cases, users only want to display certain categories in their navigation menu at the top of the page. There are limited spots, that can only be filled by top categories, but if you use the default wp_list_categories code, it will show all categories. This is why this hack below comes in very handy when you want to create a navigation menu and only display certain categories.

Note, you can also change the ‘include’ text to ‘exclude’ and show all categories and exclude those that you don’t want displayed. The numbers displayed in the code are the category IDs. Remember since WordPress shows categories in a list format, you will need to edit the CSS in order to make it work.
Display Tags In A Dropdown Menu

I never liked tag clouds, for the simple reason that most of the time, they’re aren’t readable properly. Here is the solution to this problem: Displaying tags in a dropdown menu.

The first thing to do is to create the function. Paste the following code to your functions.php file:

< ?php function dropdown_tag_cloud( $args = '' ) { $defaults = array( 'smallest' => 8, ‘largest’ => 22, ‘unit’ => ‘pt’, ‘number’ => 45,
‘format’ => ‘flat’, ‘orderby’ => ‘name’, ‘order’ => ‘ASC’,
‘exclude’ => ”, ‘include’ => ”
);
$args = wp_parse_args( $args, $defaults );

$tags = get_tags( array_merge($args, array(‘orderby’ => ‘count’, ‘order’ => ‘DESC’)) ); // Always query top tags

if ( empty($tags) )
return;

$return = dropdown_generate_tag_cloud( $tags, $args ); // Here’s where those top tags get sorted according to $args
if ( is_wp_error( $return ) )
return false;
else
echo apply_filters( ‘dropdown_tag_cloud’, $return, $args );
}

function dropdown_generate_tag_cloud( $tags, $args = ” ) {
global $wp_rewrite;
$defaults = array(
‘smallest’ => 8, ‘largest’ => 22, ‘unit’ => ‘pt’, ‘number’ => 45,
‘format’ => ‘flat’, ‘orderby’ => ‘name’, ‘order’ => ‘ASC’
);
$args = wp_parse_args( $args, $defaults );
extract($args);

if ( !$tags )
return;
$counts = $tag_links = array();
foreach ( (array) $tags as $tag ) {
$counts[$tag->name] = $tag->count;
$tag_links[$tag->name] = get_tag_link( $tag->term_id );
if ( is_wp_error( $tag_links[$tag->name] ) )
return $tag_links[$tag->name];
$tag_ids[$tag->name] = $tag->term_id;
}

$min_count = min($counts);
$spread = max($counts) – $min_count;
if ( $spread < = 0 ) $spread = 1; $font_spread = $largest - $smallest; if ( $font_spread <= 0 ) $font_spread = 1; $font_step = $font_spread / $spread;// SQL cannot save you; this is a second (potentially different) sort on a subset of data. if ( 'name' == $orderby ) uksort($counts, 'strnatcasecmp'); else asort($counts);if ( 'DESC' == $order ) $counts = array_reverse( $counts, true );$a = array();$rel = ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() ) ? ‘ rel=”tag”‘ : ”;

foreach ( $counts as $tag => $count ) {
$tag_id = $tag_ids[$tag];
$tag_link = clean_url($tag_links[$tag]);
$tag = str_replace(‘ ‘, ‘ ‘, wp_specialchars( $tag ));
$a[] = “t“;
}

switch ( $format ) :
case ‘array’ :
$return =& $a;
break;
case ‘list’ :
$return = “

    nt

  • “;
    $return .= join(“
  • nt

  • “, $a);
    $return .= “
  • n

n”;
break;
default :
$return = join(“n”, $a);
break;
endswitch;

return apply_filters( ‘dropdown_generate_tag_cloud’, $return, $tags, $args );
}
?>

Once done, you can use the function to get your dropdown menu of tags. Just open the file where you want the list to be displayed (Most of the time it is sidebar.php) and paste the following code:

source

Display Categories in a drop down Menu

To add a good looking drop down that will list all your existing categories, insert the following code in your blog template. You can do it either in your sidebar.php file or anywhere in the index.php. This is the code :-

]*)>#”, “

source

Display Archives in a drop down Menu

Just like in categories, you can have your monthly archives listed in a drop down. Add the following code to your template files :-

source

Exclude Categories From Search

If for some reason, you’d like to exclude some categories from searches, you have to tweak WordPress a bit because there’s no built-in solution to this problem. Happilly, here’s a code to do that job!

To achieve this recipe, replace the categories IDs on line 3 and paste the following code on your search.php template:

< ?php if( is_search() ) : $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts("s=$s&paged=$paged&cat=1,2,3"); endif; ?>

source
You are done!!!!!!!

Exclude Categories from your RSS Feed

Depending to your blog structure, it may be interesting to exclude some categories from your rss feeds. If you always wanted to find a clean way to do it, I’m pretty sure this recipe will make you happy.

Before starting to code, you’ll have to know the numeric ID of the categories you want to exclude. If you don’t know how to get the ID of a particular category, just read the first post in the category “WordPress Tags,Categories and Archives Hacks”.

Once you have the ID of the categories you want to exclude from your rss feed, open the functions.php file from your theme. If your theme doesn’t have a functions.php file, create one.

Paste the following code in it:

function myFilter($query) {
if ($query->is_feed) {
$query->set(‘cat’,’-5′); //Don’t forget to change the category ID =^o^=
}
return $query;
}

add_filter(‘pre_get_posts’,’myFilter’);

source

Display your categories in two columns

The stadard wp_list_categories() functions echoes a list of all your categories. Let’s see how we can easily force the display of categories on two columns.

Simply paste the following piece of code where you’d like your categories to be displayed

< ?php $cats = explode("
“,wp_list_categories(‘title_li=&echo=0&depth=1&style=none’));
$cat_n = count($cats) – 1;
for ($i=0;$i< $cat_n;$i++): if ($i<$cat_n/2): $cat_left = $cat_left.'

  • ‘.$cats[$i].”;
    elseif ($i>=$cat_n/2):
    $cat_right = $cat_right.’

  • ‘.$cats[$i].’
  • ‘;
    endif;
    endfor;
    ?>

      < ?php echo $cat_left;?>
      < ?php echo $cat_right;?>

    WordPress Comments Hacks

    WordPress Comments Hacks

    Automatically refuse spam comments on your WordPress blog

    Spam is a nuisance, and you know it. Happilly, WordPress users have Akismet, which help a lot to fight spam. But what about protecting your blog even more? This recipe might help

    Paste the following code in your functions.php. Comment that contain any of the words contained within the $bad_comment_content array will be automatically rejected.

    function in_comment_post_like($string, $array) {
    foreach($array as $ref) { if(strstr($string, $ref)) { return true; } }
    return false;
    }
    function drop_bad_comments() {
    if (!empty($_POST[‘comment’])) {
    $post_comment_content = $_POST[‘comment’];
    $lower_case_comment = strtolower($_POST[‘comment’]);
    $bad_comment_content = array(
    ‘viagra’,
    ‘hydrocodone’,
    ‘hair loss’,
    ‘[url=http’,
    ‘[link=http’,
    ‘xanax’,
    ‘tramadol’,
    ‘russian girls’,
    ‘russian brides’,
    ‘lorazepam’,
    ‘adderall’,
    ‘dexadrine’,
    ‘no prescription’,
    ‘oxycontin’,
    ‘without a prescription’,
    ‘sex pics’,
    ‘family incest’,
    ‘online casinos’,
    ‘online dating’,
    ‘cialis’,
    ‘best forex’,
    ‘amoxicillin’
    );
    if (in_comment_post_like($lower_case_comment, $bad_comment_content)) {
    $comment_box_text = wordwrap(trim($post_comment_content), 80, “n “, true);
    $txtdrop = fopen(‘/var/log/httpd/wp_post-logger/nullamatix.com-text-area_dropped.txt’, ‘a’);
    fwrite($txtdrop, ” ————–n [COMMENT] = ” . $post_comment_content . “n ————–n”);
    fwrite($txtdrop, ” [SOURCE_IP] = ” . $_SERVER[‘REMOTE_ADDR’] . ” @ ” . date(“F j, Y, g:i a”) . “n”);
    fwrite($txtdrop, ” [USERAGENT] = ” . $_SERVER[‘HTTP_USER_AGENT’] . “n”);
    fwrite($txtdrop, ” [REFERER ] = ” . $_SERVER[‘HTTP_REFERER’] . “n”);
    fwrite($txtdrop, ” [FILE_NAME] = ” . $_SERVER[‘SCRIPT_NAME’] . ” – [REQ_URI] = ” . $_SERVER[‘REQUEST_URI’] . “n”);
    fwrite($txtdrop, ‘————–**********——————‘.”n”);
    header(“HTTP/1.1 406 Not Acceptable”);
    header(“Status: 406 Not Acceptable”);
    header(“Connection: Close”);
    wp_die( __(‘bang bang.’) );
    }
    }
    }
    add_action(‘init’, ‘drop_bad_comments’);

    Source

    Number your comments
    Open comments.php and find the following line:

    < ?php foreach ($comments as $comment) : ?>

    Just above this line, initialize a counter variable:

    < ?php $i = 0; ?>

    Just after this line, increment the counter:

    < ?php $i++; ?>

    Now, you just have to echo the $i variable to get the number of the current comment. Paste this code anywhere on your comments loop:

    < ?php echo $i; ?>

    source
    Your comments are now numbered!

    Batch deleting spam comments on a WordPress blog

    delete more than 6000 spam comments that you received on your blog.

    First of it all, backup your WordPress database. Then, login to your phpmyadmin, select your WordPress blog database and click on SQL:

    Then, insert the following sql command:

    DELETE from wp_comments WHERE comment_approved = ‘0’;

    source

    All non-approved comments will be deleted. But instead of having such trouble next time, you should definitely install Akismet!

    Highlight author comments in WordPress

    This is useful to make the author comments pop in the comment section, so the readers find the answers to their questions quicker. It can also avoid people pretending they are the author by commenting with his name.

    To style the author’s comments differently, you should open the comments.php template file and look for this piece of code (or something looking like it).

  • ” id=”comment…

    Replace it by this one.

  • user_id)
    $oddcomment = “authcomment”;
    echo $oddcomment;
    ?>” id=”comment…

    Then you can style it in your stylesheet with something like this.

    .authcomment {
    background-color: #B3FFCC !important;
    }

    source

    Alternating Colors For Comments

    You might want to have alternating row colors for your comments, to make a clearer separation. Alternating rows make it easier to distinguish different comments. Doing this is relatively very easy.

    Open your theme css file, and paste this at the bottom:

    .color1 {
    background-color: #DBDBDB;
    }
    .color2 {
    background-color: #EEEEEE;
    }

    At the VERY top of comments.php file, put this on a line of it’s own.

    < ?$i;?>

    Now scroll down to find this part of the code

    < ?php foreach ($comments as $comment) : ?>

    Now replace the above by

    < ?php foreach ($comments as $comment) : ?>

    “>

    source

    Displaying Recent Comments

    Recent comments are very helpful for readers to comment on any topic about any ongoing discussion. To display your most recent comments, you will have to modify your functions.php file from the theme folder. If the functions.php file is not present, make a new text file, name it functions.php and add it to your theme folder. Add the following code to it and save the file.

    < ?php function recent_comments($src_count=10, $src_length=60, $pre_HTML='

      ‘, $post_HTML=”) {
      global $wpdb;
      $sql = “SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type,
      SUBSTRING(comment_content,1,$src_length) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = ‘1’ AND comment_type = ” AND post_password = ” ORDER BY comment_date_gmt DESC
      LIMIT $src_count”;
      $comments = $wpdb->get_results($sql);
      $output = $pre_HTML;
      foreach ($comments as $comment) {
      $output .= “

    • ID) . “#comment-” . $comment->comment_ID . “” title=”on ” . $comment->post_title . “”>” . strip_tags($comment->com_excerpt) .”…
    • “;
      }
      $output .= $post_HTML;
      echo $output;
      }
      ?>

      Now, wherever you want to show the list of recent comments, just add this code.

      < ?php recent_comments(); ?>

      source

      How to Separate WordPress Comments and Trackbacks

      Trackbacks are the messages displayed in the comments list whenever another blog links back to one of your posts. If you use trackbacks on your blog, it is best if they are not mixed with the comments. The comments are a conversation between real people. Having machine-generated links in the middle of that will only serve to disrupt the conversations.

      In order to separate the comments and trackbacks, you just need to follow these steps.

      Open comments.php, and search for the following line

      < ?php foreach ($comments as $comment) : ?>

      After it, paste the following

      < ?php $comment_type = get_comment_type(); ?>
      < ?php if($comment_type == 'comment') { ?>

      Now look for

      < ?php endforeach; /* end for each comment */ ?>

      And before it, paste

      < ?php } else { $trackback = true; } /* End of is_comment statement */ ?>

      Now your list of comments will continue to display as normal, but without any trackbacks or pingbacks. Now we will add a second comments loop for the trackbacks.

      Look for the following line

      < ?php else : // this is displayed if there are no comments so far ?>

      And before it, paste this: (The “Trackbacks” title line can be deleted if you don’t want a heading to be shown)

      < ?php if ($trackback == true) { ?>

      Trackbacks

        < ?php foreach ($comments as $comment) : ?>
        < ?php $comment_type = get_comment_type(); ?>
        < ?php if($comment_type != 'comment') { ?>

      1. < ?php comment_author_link() ?>
      2. < ?php } ?>
        < ?php endforeach; ?>

      < ?php } ?>

  • WordPress Post Hacks

    WordPress Post Hacks

    Create Your Own Popular Posts content in the sidebar

    Highlighting the most popular posts on your site is a great way to send new visitors to your very best content and win them over.

    There are a few different ways you can do this, and quite a few plugins out there to help. But why not base it on the number of comments? If you write a post that makes people talk, it must be a well written post (Most of the time…).

    Popular Posts

    Get posts published between two particular dates

    Get posts published between two particular dates

    WordPress loop is very powerful, as well as the query_posts() function, which allow you to specify some parameters for the loop to retrieve posts. Though, there’s no built-in function or parameter to get posts between two dates. Let’s solve that.

    Open your index.php file and find the loop. Just before the loop starts, paste the following code. Of course, don’t forget to change the dates on line 3 according to your needs.

    < ?php function filter_where($where = '') { $where .= " AND post_date >= ‘2009-05-01’ AND post_date < = '2009-05-15'"; return $where; } add_filter('posts_where', 'filter_where'); query_posts($query_string); ?>

    Display Sticky Posts in One Area

    Display Sticky Posts in One Area

    You can change the number 5 the amount of posts you want to show in your page. You can also display full posts by changing ‘the_excerpt’ value to ‘the_content’.

    < ?php $sticky = get_option('sticky_posts'); rsort( $sticky ); $sticky = array_slice( $sticky, 0, 5); query_posts( array( 'post__in' => $sticky, ‘caller_get_posts’ => 1 ) );
    if (have_posts()) :
    while (have_posts()) : the_post();
    the_title();
    the_excerpt();
    endwhile;
    endif;
    ?>

    Display Author Information For Posts

    Display Author Information For Posts

    By using the codes below in your single.php file, you will pull the information from the post author’s profile on your blog and show a bit about them. This is especially useful if you’ve got a lot of authors on your blog.

    how Display Author Information For Posts

    < div id="author-info">
    < div id="author-image">
    < a href="< ?php the_author_meta('user_url'); ?>“>
    < ?php echo get_avatar( get_the_author_meta('user_email'), '80', '' ); ?>< /div>
    < div id="author-bio">
    < h4>Written by < ?php the_author_link(); ?>< /h4>
    < ?php the_author_meta('description'); ?>
    < /div>
    < /div>

    Make your new posts stands out

    Make your new posts stands out

    Why not giving a special style to the posts published less than 24 hours ago, to let your readers know about the fact they’re new? Here’s a simple code to do it.

    To achieve this recipe, edit your index.php file and look for the loop. Replace it with that one:

    < ?php if (have_posts()) : ?>
    < ?php while (have_posts()) : the_post(); $currentdate = date('Y-m-d',mktime(0,0,0,date('m'),date('d'), date('Y'))); $postdate = get_the_time('Y-m-d'); if ($postdate==$currentdate) { echo '

    ‘;
    } else {
    echo ‘

    ‘;
    } ?>
    Tags Autor
    ShortURL: http://code.jar.io/?p=192
    Make your new posts stands out

    Automatically insert content after each post

    Automatically insert content after each post

    Most blogs automatically displays some text after each post, for exemple to ask readers to subscribe to their rss feed. This text is very often hardcoded. Why not using function.php instead, and be able to keep the text when you’ll switch theme?

    To achieve this recipe, simply paste the following code in your functions.php file. By using functions.php, you’ll not have to re-insert this code if you switch themes.

    function insertFootNote($content) {
    if(!is_feed() && !is_home()) {
    $content.= “

    “;
    }
    return $content;
    }
    add_filter (‘the_content’, ‘insertFootNote’);

    Display Related Posts without using Plugins

    Display Related Posts without using Plugins

    Displaying related posts is a very great way to help visitors staying longer on your blog. You can use a plugin, but you also can use tags and a custom code to show related posts. Let’s see how to do!

    This code will display related posts based on the current post tag(s). It must be pasted within the loop.

    < ?php //for use in the loop, list 5 post titles related to first tag on //current post $tags = wp_get_post_tags($post->ID);
    if ($tags) {
    echo ‘Related Posts’;
    $first_tag = $tags[0]->term_id;
    $args=array(
    ‘tag__in’ => array($first_tag),
    ‘post__not_in’ => array($post->ID),
    ‘showposts’=>5,
    ‘caller_get_posts’=>1
    );
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) : $my_query->the_post(); ?>

    Tags Autor
    ShortURL: http://code.jar.io/?p=190

    Display Related Posts without using Plugins

    Get the first Image from the Post and display it

    Get the first Image from the Post and display it

    Most WordPress users are using custom fields to display thumbs on their blog homepage. It is a good idea, but do you know that with a simple php function, you can grab the first image from the post, and display it. Just read on.

    First, paste this function on your functions.php file.

    function catch_that_image() {
    global $post, $posts;
    $first_img = ”;
    ob_start();
    ob_end_clean();
    $output = preg_match_all(‘//i’,
    $post->post_content, $matches);
    $first_img = $matches [1] [0];
    if(empty($first_img)){ //Defines a default image
    $first_img = “/images/default.jpg”;
    }
    return $first_img;
    }

    Once done, you can simply call the function within the loop to display the first image from the post:

    < ?php echo catch_that_image() ?>

    Create Your Own Popular Posts content in the sidebar

    Create Your Own Popular Posts content in the sidebar

    Highlighting the most popular posts on your site is a great way to send new visitors to your very best content and win them over.

    There are a few different ways you can do this, and quite a few plugins out there to help. But why not base it on the number of comments? If you write a post that makes people talk, it must be a well written post (Most of the time…).

    Popular Posts

      < ?php $result = $wpdb->get_results("SELECT comment_count,ID,post_title
      FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 5");
      foreach ($result as $post) {
      setup_postdata($post);
      $postid = $post->ID;
      $title = $post->post_title;
      $commentcount = $post->comment_count;
      if ($commentcount != 0) { ?>


    • < ?php echo $title ?>
      {< ?php echo $commentcount ?>}
    • < ?php } } ?>

    Caching any custom query using transients

    Caching any custom query using transients

    Is your theme using custom queries? If yes, you should definitely use the transients API to cache the queries. The following code shows how to cache a custom query. As you can see, there’s nothing complicated at all.

    < ?php // Get any existing copy of our transient data if ( false === ( $special_query_results = get_transient( 'special_query_results' ) ) ) { // It wasn't there, so regenerate the data and save the transient $special_query_results = new WP_Query( 'cat=5&order=random&tag=tech&post_meta_key=thumbnail' ); set_transient( 'special_query_results', $special_query_results ); }// Use the data like you would have normally... ?>

    Cached Tag cloud

    Cached Tag cloud

    Thanks to WordPress transients API, caching almost anything is definitely. The following example shows how to cache the good old tag cloud. Simply paste this code wherever you want you tag cloud to be displayed.

    $tag_cloud = get_transient( ‘tag_cloud’ );
    if ( false === $tag_cloud || ” === $tag_cloud ){
    $args = array(‘echo’ => false);
    $tag_cloud = wp_tag_cloud( $args );
    set_transient( ‘tag_cloud’, $tag_cloud, 60*60*12 );
    }
    echo $tag_cloud;

    Cached navigation menu

    Cached navigation menu

    Introduced in WordPress 3.0, the new menu system is definitely an improvement to WordPress. But using transients, we can even do something better, a menu with the same functionality but without the huge database requests.

    < ?php /** * Wrapper function around wp_nav_menu() that will cache the wp_nav_menu for all tag/category * pages used in the nav menus * @see http://lookup.hitchhackerguide.com/wp_nav_menu for $args * @author tott */ function hh_cached_nav_menu( $args = array(), $prime_cache = false ) { global $wp_query;$queried_object_id = empty( $wp_query->queried_object_id ) ? 0 : (int) $wp_query->queried_object_id;

    // If design of navigation menus differs per queried object use the key below
    // $nav_menu_key = md5( serialize( $args ) . ‘-‘ . $queried_object_id );

    // Otherwise
    $nav_menu_key = md5( serialize( $args ) );

    $my_args = wp_parse_args( $args );
    $my_args = apply_filters( ‘wp_nav_menu_args’, $my_args );
    $my_args = (object) $my_args;

    if ( ( isset( $my_args->echo ) && true === $my_args->echo ) || !isset( $my_args->echo ) ) {
    $echo = true;
    } else {
    $echo = false;
    }

    $skip_cache = false;
    $use_cache = ( true === $prime_cache ) ? false : true;

    // If design of navigation menus differs per queried object comment out this section
    //*
    if ( is_singular() ) {
    $skip_cache = true;
    } else if ( !in_array( $queried_object_id, hh_get_nav_menu_cache_objects( $use_cache ) ) ) {
    $skip_cache = true;
    }
    //*/

    if ( true === $skip_cache || true === $prime_cache || false === ( $nav_menu = get_transient( $nav_menu_key ) ) ) {
    if ( false === $echo ) {
    $nav_menu = wp_nav_menu( $args );
    } else {
    ob_start();
    wp_nav_menu( $args );
    $nav_menu = ob_get_clean();
    }
    if ( false === $skip_cache )
    set_transient( $nav_menu_key, $nav_menu );
    }
    if ( true === $echo )
    echo $nav_menu;
    else
    return $nav_menu;
    }

    /**
    * Invalidate navigation menu when an update occurs
    */
    function hh_update_nav_menu_objects( $menu_id = null, $menu_data = null ) {
    hh_cached_nav_menu( array( ‘echo’ => false ), $prime_cache = true );
    }
    add_action( ‘wp_update_nav_menu’, ‘hh_update_nav_menu_objects’ );

    /**
    * Helper function that returns the object_ids we’d like to cache
    */
    function hh_get_nav_menu_cache_objects( $use_cache = true ) {
    $object_ids = get_transient( ‘hh_nav_menu_cache_object_ids’ );
    if ( true === $use_cache && !empty( $object_ids ) ) {
    return $object_ids;
    }

    $object_ids = $objects = array();

    $menus = wp_get_nav_menus();
    foreach ( $menus as $menu_maybe ) {
    if ( $menu_items = wp_get_nav_menu_items( $menu_maybe->term_id ) ) {
    foreach( $menu_items as $menu_item ) {
    if ( preg_match( “#.*/category/([^/]+)/?$#”, $menu_item->url, $match ) )
    $objects[‘category’][] = $match[1];
    if ( preg_match( “#.*/tag/([^/]+)/?$#”, $menu_item->url, $match ) )
    $objects[‘post_tag’][] = $match[1];
    }
    }
    }
    if ( !empty( $objects ) ) {
    foreach( $objects as $taxonomy => $term_names ) {
    foreach( $term_names as $term_name ) {
    $term = get_term_by( ‘slug’, $term_name, $taxonomy );
    if ( $term )
    $object_ids[] = $term->term_id;
    }
    }
    }

    $object_ids[] = 0; // that’s for the homepage

    set_transient( ‘hh_nav_menu_cache_object_ids’, $object_ids );
    return $object_ids;
    }

    RSS subscribers count using WordPress transients

    RSS subscribers count using WordPress transients

    Using exactly the same technique as demonstrated above, we can grab RSS subscribers and store the result in WordPress database. Don’t forget to update the code with your own feedburner url on line 2. Then, paste the code where you’d like to display how many RSS feed readers you have.

    function feed_subscribers(){
    $feed_url = ‘http://feeds.feedburner.com/yourname’;
    $count = get_transient(‘feed_count’);
    if ($count != false) return $count;
    $count = 0;
    $data = wp_remote_get(‘http://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=’.$feed_url.”);
    if (is_wp_error($data)) {
    return ‘error’;
    }else{
    $body = wp_remote_retrieve_body($data);
    $xml = new SimpleXMLElement($body);
    $status = $xml->attributes();
    if ($status == ‘ok’) {
    $count = $xml->feed->entry->attributes()->circulation;
    } else {
    $count = 300; // fallback number
    }
    }
    set_transient(‘feed_count’, $count, 60*60*24); // 24 hour cache
    echo $count;
    }

    Twitter followers count using WordPress transients

    Twitter followers count using WordPress transients

    Many blogs, including this one, are displaying how many people are following them on Twitter. It’s quite easy to grab some json data, but it takes a significant amount of time. Using transients allow you to grab the json data from Twitter once a day, and store it in your database for future uses.

    Simply paste the function below into your functions.php file:

    function my_followers_count($screen_name = ‘kovshenin’){
    $key = ‘my_followers_count_’ . $screen_name;

    // Let’s see if we have a cached version
    $followers_count = get_transient($key);
    if ($followers_count !== false)
    return $followers_count;
    else
    {
    // If there’s no cached version we ask Twitter
    $response = wp_remote_get(“http://api.twitter.com/1/users/show.json?screen_name={$screen_name}”);
    if (is_wp_error($response))
    {
    // In case Twitter is down we return the last successful count
    return get_option($key);
    }
    else
    {
    // If everything’s okay, parse the body and json_decode it
    $json = json_decode(wp_remote_retrieve_body($response));
    $count = $json->followers_count;

    // Store the result in a transient, expires after 1 day
    // Also store it as the last successful using update_option
    set_transient($key, $count, 60*60*24);
    update_option($key, $count);
    return $count;
    }
    }
    }

    echo “I have ” . my_followers_count(‘kovshenin’) . ” followers”;

    List sites from your network

    List sites from your network

    Let’s start with an interesting snippet for those who run networks of many blogs. The code below display a general menu of all sites from your networks. In this case, transients are used to store the data for a defined time (which can be set using the $expires variable on line 1) so you’ll not make huge database calls each time your menu have to be displayed.

    To use this snippet, first you have to paste the function into your functions.php file.

    function wp_list_sites( $expires = 7200 ) {
    if( !is_multisite() ) return false;

    // Because the get_blog_list() function is currently flagged as deprecated
    // due to the potential for high consumption of resources, we’ll use
    // $wpdb to roll out our own SQL query instead. Because the query can be
    // memory-intensive, we’ll store the results using the Transients API
    if ( false === ( $site_list = get_transient( ‘multisite_site_list’ ) ) ) {
    global $wpdb;
    $site_list = $wpdb->get_results( $wpdb->prepare(‘SELECT * FROM wp_blogs ORDER BY blog_id’) );
    // Set the Transient cache to expire every two hours
    set_site_transient( ‘multisite_site_list’, $site_list, $expires );
    }

    $current_site_url = get_site_url( get_current_blog_id() );

    $html = ‘

      ‘ . “n”;

      foreach ( $site_list as $site ) {
      switch_to_blog( $site->blog_id );
      $class = ( home_url() == $current_site_url ) ? ‘ class=”current-site-item”‘ : ”;
      $html .= “t” . ‘

    • ‘ . get_bloginfo(‘name’) . ‘
    • ‘ . “n”;
      restore_current_blog();
      }

      $html .= ‘

    ‘ . “nn”;

    return $html;
    }

    Once done, the following code will display all sites from your network. Simply paste it on any of theme files, where you want the list to be displayed.

    < ?php // Multisite Network Menu $network_menu = wp_list_sites(); if( $network_menu ): ?>

    < ?php echo $network_menu; ?>

    < ?php endif; ?>

    Remove dashboard widgets according to user role

    Remove dashboard widgets according to user role

    If you’re owning a multi-user blog, it may be useful to know how to hide some dashboard widgets to keep confidential information in a safe place.
    The following code will remove the postcustom meta box for “author” (role 2). To apply the hack on your own blog, just copy the code below and paste it in your functions.php file.

    function customize_meta_boxes() {
    //retrieve current user info
    global $current_user;
    get_currentuserinfo();

    //if current user level is less than 3, remove the postcustom meta box
    if ($current_user->user_level < 3) remove_meta_box('postcustom','post','normal'); }add_action('admin_init','customize_meta_boxes');

    Monitor your server in WordPress dashboard

    Monitor your server in WordPress dashboard

    WordPress dashboard API allow you to do many useful things using dashboard widgets. I recently came across this very useful code: a dashboard widget that allows you to monitor your server directly on WordPress’ dashboard.
    Paste the code in your functions.php file, and you’re done.

    function slt_PHPErrorsWidget() {
    $logfile = ‘/home/path/logs/php-errors.log’; // Enter the server path to your logs file here
    $displayErrorsLimit = 100; // The maximum number of errors to display in the widget
    $errorLengthLimit = 300; // The maximum number of characters to display for each error
    $fileCleared = false;
    $userCanClearLog = current_user_can( ‘manage_options’ );
    // Clear file?
    if ( $userCanClearLog && isset( $_GET[“slt-php-errors”] ) && $_GET[“slt-php-errors”]==”clear” ) {
    $handle = fopen( $logfile, “w” );
    fclose( $handle );
    $fileCleared = true;
    }
    // Read file
    if ( file_exists( $logfile ) ) {
    $errors = file( $logfile );
    $errors = array_reverse( $errors );
    if ( $fileCleared ) echo ‘

    File cleared.

    ‘;
    if ( $errors ) {
    echo ‘

    ‘.count( $errors ).’ error’;
    if ( $errors != 1 ) echo ‘s’;
    echo ‘.’;
    if ( $userCanClearLog ) echo ‘ [ CLEAR LOG FILE ]’;
    echo ‘

    ‘;
    echo ‘

    ‘;
    echo ‘

      ‘;
      $i = 0;
      foreach ( $errors as $error ) {
      echo ‘

    1. ‘;
      $errorOutput = preg_replace( ‘/[([^]]+)]/’, ‘[$1]‘, $error, 1 );
      if ( strlen( $errorOutput ) > $errorLengthLimit ) {
      echo substr( $errorOutput, 0, $errorLengthLimit ).’ […]’;
      } else {
      echo $errorOutput;
      }
      echo ‘
    2. ‘;
      $i++;
      if ( $i > $displayErrorsLimit ) {
      echo ‘

    3. More than ‘.$displayErrorsLimit.’ errors in log…
    4. ‘;
      break;
      }
      }
      echo ‘

    ‘;
    } else {
    echo ‘

    No errors currently logged.

    ‘;
    }
    } else {
    echo ‘

    There was a problem reading the error log file.

    ‘;
    }
    }

    // Add widgets
    function slt_dashboardWidgets() {
    wp_add_dashboard_widget( ‘slt-php-errors’, ‘PHP errors’, ‘slt_PHPErrorsWidget’ );
    }
    add_action( ‘wp_dashboard_setup’, ‘slt_dashboardWidgets’ );

    Provide help messages

    Provide help messages

    If you’re building a site for a client and they have some problems with some parts of the dashboard, a good idea is to provide contextual help to the client.
    The following hack will allow you to add a custom help messages for the blog admin. As usual, you only have to paste the code into your functions.php file.

    function my_admin_help($text, $screen) {
    // Check we’re only on my Settings page
    if (strcmp($screen, MY_PAGEHOOK) == 0 ) {

    $text = ‘Here is some very useful information to help you use this plugin…’;
    return $text;
    }
    // Let the default WP Dashboard help stuff through on other Admin pages
    return $text;
    }

    add_action( ‘contextual_help’, ‘my_admin_help’ );