Skip to content

10 Useful WordPress Search Code Snippets

setembro 25, 2010

Post Ctrl+C,Ctrl+V from

It is no secret that the standard search within WordPress is not very accurate. The problem is that WordPress takes your search term far too literally, meaning, that if you were to type “search+code+wordpress” in to our search box above, it would return every post that contains those terms (in this case over 30 posts), even though we have no such post with in our database. So, in actual fact even though there are over 30+ results, our reader will never actually find what they are looking for. We have to improve this.

In this post we have 10 really useful code snippets that will help improve your WordPress Search functionality.

How To Exclude Posts or Pages from Search Results

If you would like to be able to control which posts or pages should be excluded from WordPress search results, all you have to do is copy and paste the code below into your functions.php file.

In this snippet, posts with the IDs 0 and 1 will be excluded. Edit accordingly to suit your needs.

1 function SearchFilter($query) {
2 if ($query->is_search) {
3 $query->set('cat','0,1');
4 }
5 return $query;
6 }
8 add_filter('pre_get_posts','SearchFilter');

Source: →

WordPress Drop-Down Category Search Form

A useful function you could give to your WordPress search would be to allow your readers to filter the search results by targeting a specific category. This can be achieved by using a simple drop-down containing all of the category titles.

All you have to do is replace the standard WordPress search form (found within the searchform.php) with the snippet below:

1 <form role="search" method="get" id="searchform" action="<?php bloginfo('siteurl'); ?>">
2 <div>
3 <label class="screen-reader-text" for="s">Search for:</label>
4 <input type="text" value="" name="s" id="s" />
5 in <?php wp_dropdown_categories( 'show_option_all=All Categories' ); ?>
6 <input type="submit" id="searchsubmit" value="Search" />
7 </div>
8 </form>

Source: →

Dynamically Search Categories and Child Categories Only

This search form snippet could be useful within the category archive to allow your readers to search the child categories from any given parent category.

In this snippet, all child categories from category ID 1 will be searched. Edit accordingly to suit your needs.

01 <form method=”get” id=”searchform” action=”<?php bloginfo(‘home’); ?>/”>
02 <div id=”search”>
03 <input type=”text” value=”Search… ” onclick=”this.value=”;” name=”s” id=”s” />
04 <?php $categories = get_categories(‘child_of=1′);
05 $catlist = ”;
06 foreach ($categories as $cat) {
07 $catlist.= $cat->cat_ID.’,';
08 }
09 $catlist.’5′;
10 ?>
11 <input type=”hidden” name=”cat” value=”<?php echo $catlist”?>” />
12 <input name=”" type=”image” src=”<?php bloginfo(‘stylesheet_directory’); ?>/styles/<?php echo $style_path”; ?>/search.gif” value=”Go” class=”btn” />
13 </div><!–/search –>
14 </form>

Source: →

Search a Specific Post Type

WordPress gives you the ability to search specific post types by using this small snippet.

All you have to do is copy and paste the code below into your functions.php file.

01 function SearchFilter($query) {
02 if ($query->is_search) {
03 // Insert the specific post type you want to search
04 $query->set('post_type', 'feeds');
05 }
06 return $query;
07 }
09 // This filter will jump into the loop and arrange our results before they're returned
10 add_filter('pre_get_posts','SearchFilter');

Source: →

Display the Number of Search Results Returned

If you would like to show your readers how many results have been found per search term, you could use this helpful snippet.

Open search.php and locate the following:

1 <h2 class="pagetitle">Search Results</h2>

And replace it with this code:

1 <h2 class="pagetitle">Search Result for <?php /* Search Count */ $allsearch = &new WP_Query("s=$s&showposts=-1"); $key = wp_specialchars($s, 1); $count = $allsearch->post_count; _e(''); _e('<span>'); echo $key; _e('</span>'); _e(' &mdash; '); echo $count . ' '; _e('articles'); wp_reset_query(); ?></h2>

Source: →

Highlight WordPress Search Terms with jQuery

To help make your search results that little bit clearer to your readers, you could use this snippet which will highlight the searched term within the results.

Copy and paste the following code into your theme’s functions.php file:

01 function hls_set_query() {
02 $query = attribute_escape(get_search_query());
04 if(strlen($query) > 0){
05 echo '
06 <script type="text/javascript">
07 var hls_query  = "'.$query.'";
08 </script>
09 ';
10 }
11 }
13 function hls_init_jquery() {
14 wp_enqueue_script('jquery');
15 }
17 add_action('init', 'hls_init_jquery');
18 add_action('wp_print_scripts', 'hls_set_query');

And then add this code into your header.php file, just before the /head tag:

01 <style type="text/css" media="screen">
02 .hls { background: #D3E18A; }
03 </style>
04 <script type="text/javascript">
05 jQuery.fn.extend({
06 highlight: function(search, insensitive, hls_class){
07 var regex = new RegExp("(<[^>]*>)|(\\b"+ search.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1") +")", insensitive ? "ig" : "g");
08 return this.html(this.html().replace(regex, function(a, b, c){
09 return (a.charAt(0) == "<") ? a : "<strong class=\""+ hls_class +"\">" + c + "</strong>";
10 }));
11 }
12 });
13 jQuery(document).ready(function($){
14 if(typeof(hls_query) != 'undefined'){
15 $("#post-area").highlight(hls_query, 1, "hls");
16 }
17 });
18 </script>

Source: →

Disable WordPress Search

If you are looking for a way to disable all of WordPress’ search functionality, you could use this small snippet.

All you have to do is copy and paste the code below into your functions.php file.

01 function fb_filter_query( $query, $error = true ) {
03 if ( is_search() ) {
04 $query->is_search = false;
05 $query->query_vars[s] = false;
06 $query->query[s] = false;
08 // to error
09 if ( $error == true )
10 $query->is_404 = true;
11 }
12 }
14 add_action( 'parse_query', 'fb_filter_query' );
15 add_filter( 'get_search_form', create_function( '$a', "return null;" ) );

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 snippet allows your search to return unlimited results.

In search.php you can add the following code above the loop for this functionality.

First of all find this code within search.php:

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

And then add this code:

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

Source: →

Implement Google AJAX Search API

Implement Google AJAX Search APIImplement Google AJAX Search API →
Demo →
Google provides an awesome method in which you can use their search for your own site: the Google AJAX Search API. In this advanced tutorial you will be shown how to implement this awesome API within your own website.
Google’s AJAX Search API requires that you sign up for an API key, you can get it here: Google AJAX Search API

Create an Ajax-based Auto-completing Search Field for WordPress

Create an Ajax-based Auto-completing Search Field for WordPressCreate an Ajax-based Auto-completing Search Field for WordPress →
When someone starts to type with the search field they will be presented with a drop-down box offering suggestions. This tutorial will show you how to implement thsi on your own site.
Please note that even if this code is fully functional, this is an experimentation, and the SQL query isn’t really optimized.

How To Add Google Custom Search To WordPress

How To Add Google Custom Search To WordPressGoogle Custom Search Engine →
In this tutorial you will be shown how to integrate Google’s Custom Search Engine into your blog, making it easier for your readers to find content and allow you to make some money with Adsense.
How To Add Google Custom Search To WordPress →


Esconder informações sobre a versão do wordpress e sobre o tema em uso

agosto 21, 2010

O objetivo é esconder informações sobre a versão do wordpress e sobre o tema em uso

No arquivo wp-admin/includes/dashboard.php

  • Comenta a linha 367 (versão 3.0.1)
    //printf(_n(‘Theme <span>%1$s</span> with <span>%2$s Widget</span>’, ‘Theme <span>%1$s</span> with <span>%2$s Widgets</span>’, $num_widgets), $switch_themes, $num);}
    para não exibir o thema atual
  • Na linha 378 (versão 3.0.1)
    Acrescenta um if para que usuários pouco privilegiados não vejam  a mensagem que o wordpress precisa ser atualizado
    if ( current_user_can( ‘switch_themes’) ) {


Hide Update Reminder

Hides the Update Reminder in the Admin for all non Admin users.

This plugin allows you to hide the update WordPress reminder from all users that are not assumed Administrators (cannot upgrade plugins).

If you have multiple users then this means those who are not admins don’t need to see the message. Useful for CMS based sites, so the client doesn’t see the notice.

Author: sarahg111

15 fantásticos comandos SQL para WordPress

agosto 8, 2010

Você encontra este artigo, mais bonito e organizado, e quem sabe até mais atualizado em:

Para quem faz uso um pouco mais avançado do WordPress, especialmente quem trabalha desenvolvendo sites com a plataforma, é bem comum aparecerem situações um tanto complexas. Para estas questões, seguem 13 fantásticos comandos SQL para WordPress!

Este é um artigo traduzido do original “13 Useful WordPress SQL Queries You Wish You Knew Earlier“, do blog Onextrapixel, e sofreu algumas adaptações.

Uma maneira prática de executar comandos SQL é através do phpMyAdmin. Até a hospedagem mais básica dá acesso à ferramenta de banco de dados, então não há dificuldades nisso. Uma vez no sistema, você deve selecionar aba “SQL” e escrever/colar a instrução SQL que deseja executar.

13 fantásticos comandos SQL para WordPress: aba SQL do phpMyAdmin

Os comandos SQL para WordPress a seguir são para o prefixo padrão do WordPress “wp_”. Caso o prefixo de suas tabelas seja diferente (o que é recomendado, por questões de segurança), faça os devidos complementos necessários às queries.

1. Alterar siteurl e homeurl

WordPress armazena o caminho absoluto da URL do site (“siteurl”) e URL da home (“homeurl”) no banco de dados. Portanto, se você transferir o seu site WordPress do localhost para o servidor, por exemplo, o site não vai carregar! Isso ocorre porque o caminho absoluto ainda está apontando para o seu localhost. Você vai precisar executar um comando para resolver isso.

UPDATE wp_options
SET option_value = REPLACE(option_value, '', '')
WHERE option_name = 'home'
OR option_name = 'siteurl';

2. Alterar GUID

Depois de migrar seu blog a partir de, por exemplo, localhost, para o servidor ou de um outro domínio para um novo domínio, você terá que corrigir as URLs para o campo GUID na tabela wp_posts. Isto é crucial, porque GUID é usado para montar o slug de seu post do caminho absoluto do artigo correto.

UPDATE wp_posts
SET guid = REPLACE (guid, '', '');

3. Alterar URL no conteúdo

O WordPress utiliza caminhos absolutos no URL ao invés de um caminho relativo quando vai armazená-los no banco de dados. Dentro do conteúdo de cada registro de artigo, ele armazena todas as URLs antigas referenciando as fontes antigas. Portanto, você precisará alterar todas essas URLs com o endereço do novo domínio.

UPDATE wp_posts
SET post_content = REPLACE (post_content, '', '');

4. Alterar apenas o caminho das imagens

Caso seja preciso alterar o domínio das imagens inseridas nas páginas e artigos, esta solução vai ajudar você a fazer isso de forma simples.

UPDATE wp_posts
SET post_content = REPLACE (post_content, 'src="', 'src="');

Também é preciso atualizar o GUID para o tipo “attachment” com a seguinte instrução SQL:

UPDATE wp_posts
SET guid = REPLACE (guid, '', '') WHERE post_type = 'attachment';

5. Atualizar Post Meta

Atualizar Post Meta funciona quase da mesma maneira como atualizar a URL no conteúdo do post. Se você tiver dados extras para cada post, você pode usar a seguinte instrução para alterar todos eles.

UPDATE wp_postmeta
SET meta_value = REPLACE (meta_value, '','');

6. Alterar o nome usuário padrão “admin”

Apesar de que na versão 3 do WordPress o usuário “admin” poderá ser alterado no momento da instalação, não custa deixar para a posteridade a dica de como alterar o nome do “admin”.

UPDATE wp_users
SET user_login = 'nomequevocequiser'
WHERE user_login = 'Admin';

7. Resetar password

Já quis resetar sua senha no WordPress mas, por algum motivo, não conseguiu usar a seção para resetar o password? Eis a solução:

UPDATE wp_users
SET user_pass = MD5('senha')
WHERE user_login = 'login';

8. Transferir artigos de um autor para outro

Para transferir os artigos de um autor para outro, você gasta um tempo enorme se fizer isso manualmente. Com o comando SQL a seguir, é possível fazer isso facilmente. Para a dica, é preciso saber o ID dos autores.

UPDATE wp_posts
SET post_author = 'id_novo_autor'
WHERE post_author = 'id_autor_antigo';

9. Apagar revisões

Quando se está editando um artigo no WordPress, é comum cópias de segurança serem feitas para garantir o trabalho feito. São as chamadas “revisões”. Com o tempo, o número de registros de revisões fica grande e isso pode comprometer a performance do banco de dados. Para apagar todas as revisões de artigos, dê o seguinte comando SQL:

DELETE a,b,c FROM wp_posts a
LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id)
LEFT JOIN wp_postmeta c ON (a.ID = c.post_id)
WHERE a.post_type = 'revision'

10. Apagar post meta

Instalar e remover plugins é algo corriqueiro quando se trabalha com WordPress. Alguns plugins precisam de criar alguns post meta para funcionarem corretamente e, para esses casos, não é raro o acontecimento de, mesmo depois de o plugin ser desinstalado, algum “garbage meta” ficar enchendo o BD desnecessariamente. Uma limpeza em algum valor de post meta, às vezes, se faz necessária.

DELETE FROM wp_postmeta
WHERE meta_key = 'nome-chave-meta';

11. Exportar todos os e-mails de comentários

Quanto mais tempo seu blog/site fica no ar, é provável que mais comentários receba nos artigos publicados. Se, por algum motivo, for preciso uma listagem com e-mail de todas as pessoas que já comentaram até então, basta executar o seguinte comando:

SELECT DISTINCT comment_author_email
FROM wp_comments;

Uma vez que a listagem esteja concluída, exporte tudo através do phpMyAdmin.

12. Apagar todos pingbacks

A medida que o site/blog fica no ar – e se você tiver bom conteúdo a oferecer – o número de pingbacks começa a influenciar a qualidade do banco de dados. Para apagar todos pingbacks, proceda da seguinte maneira:

DELETE FROM wp_comments WHERE comment_type = 'pingback';

13. Apagar todos comentários de SPAM

Sem maiores explicações, eis a maneira de deletar todos os comentários marcados como SPAM:

DELETE FROM wp_comments
WHERE comment_approved = 'spam';

14. Identificar tags não usadas

Num banco de dados WordPress, se você executar alguma query SQL para apagar posts, as tags relacionadas não serão apagadas e continuarão aparecendo na nuvem de sugestão de tags e listagem de tags. Para identificar esse tipo de tag, execute a seguinte instrução SQL:

SELECT * FROM wp_terms wt
INNER JOIN wp_term_taxonomy wtt
ON wt.term_id=wtt.term_id
WHERE wtt.taxonomy='post_tag'
AND wtt.count=0;
Lembre-se: é sempre bom fazer um backup completo de seu banco de dados antes de executar queries SQL (principalmente se você não souber muito bem o que está fazendo)!

headers already sent

julho 19, 2010

Maldito “Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent”

Usando o notepad++ marcando a opção mostrada na imagem abaixo, o maldito warning sumiu.

Entenda melhor:

flash upload Erro de HTTP

julho 11, 2010

Adiciona isso no seu arquivo .htaccess

#BEGIN Image Upload HTTP Error Fix

SecFilterEngine Off

SecFilterScanPOST Off

#END Image Upload HTTP Error Fix


Obs.: Dá ultima vez que tentei (2011/12/01) deu internal server error

query_posts and get_posts

março 27, 2010
WordPress query_posts and get_posts

The WordPress query_posts command allows you to query the WordPress wp_posts database and retrieve post objects (e.g. posts, pages, attachments) based on their attributes.

query_posts is used throughout the WordPress administration system, but it is most prominent in the WordPress Loop and underlies all of the WordPress Loop commands, e.g. the_post or the_title.

get_posts is similar to query_posts and is also used to query the wp_posts database. You will note however, that the argument list it uses is slightly different compared to query_posts, therefore make sure to refer to the WordPress codex to ensure that you are using the right argument names for each of these commands.

Both query_posts and get_posts are based on the WP_Query object. However, query_posts creates a global WP_Query object that is stored in the $wp_query global variable, whereas get_posts creates a local WP_Query object that only exists within the function.

The global $wp_query variable is later used by multiple functions within the WordPress Loop. That is why it is important NOT to use query_posts within an existing WordPress Loop because it will replace the existing Loop object (contained in $wp_query) with a new WP_Query object.

query_posts is most useful when you are writing a plugin, and want to display a list of post objects within a WordPress administration menu. In the administration area, there is no Loop to worry about.

When you are operating outside of the WordPress administration area (i.e. WordPress Dashboard), it is best to use the get_posts command so that you do not inadvertently corrupt your WordPress Loop.

Incidentally, if you want to use query_posts type attributes within a WordPress Loop, then you can just create your own local WP_Query object as follows –

    $tmp_query = new WP_Query;
    return $tmp_query->query($atts);

$atts should contain an attribute array similar to what you would use in the query_posts function. Here are the list of parameters for query_posts.

Here is another example –

    $tmp_query = new WP_Query;
    $tmp_result = $tmp_query->query('category_name=aciform');


março 27, 2010


Template Tags/get posts


This is a simple tag for creating multiple loops.


<?php get_posts('arguments'); ?>


Posts list with offset

If you have your blog configured to show just one post on the front page, but also want to list links to the previous five posts in category ID 1, you can use this:

 global $post;
 $myposts = get_posts('numberposts=5&offset=1&category=1');
 foreach($myposts as $post) :
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
 <?php endforeach; ?>

Note: With use of the offset, the above query should be used only on a category that has more than one post in it, otherwise there’ll be no output.

Reset after Postlists with offset

If you need after the loop, the post you had before joining the foreach, you can use this:

 global $post;
 $tmp_post = $post;
 $myposts = get_posts('numberposts=5&offset=1&category=1');
 foreach($myposts as $post) :
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
 <?php endforeach; ?>
 <?php $post = $tmp_post; ?>

Access all post data

Some post-related data is not available to get_posts by default, such as post content through the_content(), or the numeric ID. This is resolved by calling an internal function setup_postdata(), with the $post array as its argument:

 $lastposts = get_posts('numberposts=3');
 foreach($lastposts as $post) :
 <h2><a href="<?php the_permalink(); ?>" id="post-<?php the_ID(); ?>"><?php the_title(); ?></a></h2>
 <?php the_content(); ?>
 <?php endforeach; ?>

To access a post’s ID or content without calling setup_postdata(), or in fact any post-specific data (data retained in the posts table), you can use $post->COLUMN, where COLUMN is the table column name for the data. So $post->ID holds the ID, $post->post_content the content, and so on. To display or print this data on your page use the PHP echo command, like so:

 <?php echo $post->ID; ?> 

Latest posts ordered by title

To show the last ten posts sorted alphabetically in ascending order, the following will display their post date, title and excerpt:

 $postslist = get_posts('numberposts=10&order=ASC&orderby=title');
 foreach ($postslist as $post) : 
 <?php the_date(); ?>
 <br />
 <?php the_title(); ?>   
 <?php the_excerpt(); ?>
 <?php endforeach; ?>

Note: The orderby parameter was modified in Version 2.6. This code is using the new orderby format. See Parameters for details.

Random posts

Display a list of 5 posts selected randomly by using the MySQL RAND() function for the orderby parameter value:

 <ul><li><h2>A random selection of my writing</h2>
 $rand_posts = get_posts('numberposts=5&orderby=rand');
 foreach( $rand_posts as $post ) :
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
 <?php endforeach; ?>

Show all attachments

Do this outside any Loops in your template.


$args = array(
	'post_type' => 'attachment',
	'numberposts' => -1,
	'post_status' => null,
	'post_parent' => null, // any parent
$attachments = get_posts($args);
if ($attachments) {
	foreach ($attachments as $post) {
		the_attachment_link($post->ID, false);


Show attachments for the current post

Do this inside The_Loop (where $post->ID is available).


$args = array(
	'post_type' => 'attachment',
	'numberposts' => -1,
	'post_status' => null,
	'post_parent' => $post->ID
$attachments = get_posts($args);
if ($attachments) {
	foreach ($attachments as $attachment) {
		echo apply_filters('the_title', $attachment->post_title);
		the_attachment_link($attachment->ID, false);


Parameters: WordPress 2.6+

In addition to the parameters listed below under “WordPress 2.5 And Older“, get_posts() can also take the parameters that query_posts() can since both functions now use the same database query code internally.

Note: Version 2.6 changed a number of the orderby options. Table fields that begin with post_ no longer have that part of the name. For example, post_title is now title and post_date is now date.

Parameters: WordPress 2.5 And Older

(integer) (optional) Number of posts to return. Set to 0 to use the max number of posts per page. Set to -1 to remove the limit.

Default: 5
(integer) (optional) Offset from latest post.

Default: 0
(integer) (optional) Only show posts from this category ID. Making the category ID negative (-3 rather than 3) will show results not matching that category ID. Multiple category IDs can be specified by separating the category IDs with commas – but an array of IDs does not work.

Default: None
(string) (optional) Only show posts from this category name or category slug.

Default: None
(string) (optional) Only show posts with this tag slug. If you specify multiple tag slugs separated by commas, all results matching any tag will be returned. If you specify multiple tag slugs separated by spaces, the results will match all the specified tag slugs.

Default: None
(string) (optional) Sort posts by one of various values (separated by space), including:
  • 'author' – Sort by the numeric author IDs.
  • 'category' – Sort by the numeric category IDs.
  • 'content' – Sort by content.
  • 'date' – Sort by creation date.
  • 'ID' – Sort by numeric post ID.
  • 'menu_order' – Sort by the menu order. Only useful with pages and attachments.
  • 'mime_type' – Sort by MIME type. Only useful with attachments.
  • 'modified' – Sort by last modified date.
  • 'name' – Sort by stub.
  • 'parent' – Sort by parent ID.
  • 'password' – Sort by password.
  • 'rand' – Randomly sort results.
  • 'status' – Sort by status.
  • 'title' – Sort by title.
  • 'type' – Sort by type.


  • Sorting by ID and rand is only available starting with Version 2.5.
Default: post_date
(string) (optional) How to sort $orderby. Valid values:

  • 'ASC' – Ascending (lowest to highest).
  • 'DESC' – Descending (highest to lowest).
Default: DESC
(string) (optional) The IDs of the posts you want to show, separated by commas and/or spaces. The following value would work in showing these six posts:

  • ‘45,63, 78 94 ,128 , 140’

Note: Using this parameter will override the numberposts, offset, category, exclude, meta_key, meta_value, and post_parent parameters.

Default: None
(string) (optional) The IDs of any posts you want to exclude, separated by commas and/or spaces (see $include parameter).

Default: None
$meta_key and $meta_value
(string) (optional) Only show posts that contain a meta (custom) field with this key and value. Both parameters must be defined, or neither will work.

Default: None
(string) (optional) The type of post to show. Available options are:

  • post – Default
  • page
  • attachment
  • any – all post types
Default: post
(string) (optional) Show posts with a particular status. Multiple statuses can be given, separated with a comma. Available options are:

  • publish – Default
  • private
  • draft
  • future
  • inherit – Default if $post_type is set to attachment
  • (blank) – all statuses
Default: publish
(integer) (optional) Show only the children of the post with this ID

Default: None
(boolean) (optional) Enable or disable paging. If paging is disabled, the $numberposts option is ignored.

Default: None
%d blogueiros gostam disto: