add_action add_filter
Hooks: Actions e Filters
Classes e Funções usadas: actions, add_action, add_filter, filters, hooks, the_content
Categoria: Codex | Nenhum comentário
Um importante recurso a ser explorado para o desenvolvimento de soluções no WordPress é a utilização dosHooks que o sistema disponibiliza. Os Hooks são certas funções e identificadores que servem como ganchos (dada sua nomenclatura) para execução de instruções personalizadas. Significa dizer que através do uso dos hooks é possível informar ao sistema quando e como ele deve chamar determinada função.
Existem dois tipos de ganchos oferecidos pelo WordPress: Actions e Filters. As Actions, são ações executadas em determinados momentos pelo sistema; são atividades executadas mediante o disparar de um evento, como por exemplo o publicar de um post.
Os Filters, são os filtros da informação; através de suas aplicações o desenvolvedor consegue modificar ou como o próprio nome diz, filtrar os dados enviados pelo usuário ou resgatados do banco de dados antes que estes sejam exibidos ou armazenados.
Motivos para utilização dos Hooks
Em alguns casos quando se faz necessário alterar o modo de funcionamento do WordPress, é comum desenvolvedores realizarem tais alterações diretamente no código-fonte do CMS. No entanto essa prática é pouco recomendada, pois assim que o sistema for atualizado é bem provável que as alterações se percam e tenham que ser realizadas novamente. Usar os ganchos do WordPress é um jeito seguro de alterar o comportamento e as atividades executadas pela ferramenta.
A própria programação do sistema é realizada em grande parte com base nos Hooks. Veja por exemplo a utilização das Include Tags que se baseiam nesse princípio, assim como a incorporação de scripts ao WordPress que ocorre em razão do uso de ganchos.
Actions – Eventos do WordPress
Para adicionar ações ao WordPress é preciso fazer uso da função add_action via programação PHP com os seguintes parâmetros:
add_action ( 'nome_do_gancho', 'sua_funcao', [prioridade], [argumentos_aceitos] );
- Nome do gancho – Um evento fornecido pelo sistema (veja a Referência de ações no Codex), a ele será incorporada sua função;
- Sua função – Ao disparar do referido evento, a função aqui atribuída será executada;
- Prioridade – Determina a ordem de execução das funções associadas ao gancho, por padrão seu valor é 10. Números menores são executados primeiro, e em caso de valores iguais respeita-se a ordem de adição das funções;
- Argumentos aceitos – Número inteiro que determina a quantidade de argumentos a serem passados para a função, possui valor 1 como padrão.
Estilo personalizado para a tela de login
Em um exemplo de aplicação, é possível editar a tela de login do seu template incorporando uma folha de estilo específica na página de entrada do sistema mediante o uso de:
function add_login_style() { wp_enqueue_style( 'login' ); } add_action( 'login_head', 'add_login_style' );
Os parâmetros Prioridade e Argumentos aceitos são opcionais, caso não os informe, os valores padrões serão adotados para a ação criada.
Filters – Filtrando informação
De maneira semelhante a incorporação de ações ao sistema, para se incluir um filtro a ele é preciso fazer uso da função add_filter e seus respectivos parâmetros:
add_filter ( 'nome_do_gancho', 'sua_funcao', [prioridade], [argumentos_aceitos] );
Uma grande diferença na função a ser utilizada é que ela deverá possuir um valor de retorno ou de impressão usando os recursos return ou echo do PHP, por exemplo. Assim como para as Actions, os valores Prioridade eArgumentos aceitos da função que adiciona os Filters, são opcionais.
Alterando a exibição do conteúdo
Para demonstrar a utilização dos filtros, o exemplo abaixo irá suprimir todas as tags HTML do conteúdo dos posts resgatados antes de exibí-los para o visitante:
function content_only_text( $content ) { return strip_tags( $content ); } add_filter( 'the_content', 'content_only_text' ); Fonte: http://www.guiawp.com.br/codex/hooks-actions-filters/
=================================================
=================================================
=================================================
Michael Fields
Hi Betsy, I hope this explains everything!
So, are filters a subset of actions?
They are basically the same function applied to different contexts. If you take a peek into the core, you will see that add_action is actually a wrapper function for add_filter:
function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) { return add_filter($tag, $function_to_add, $priority, $accepted_args); }
it seems I could use an action to change the text of the post for instance, instead of a filter?
Actually, you would use a filter for this situation. Let’s pretend that WordPress is a Mexican restaurant and we have ordered a taco as illustrated by the following code…
<?php $taco = 'chicken'; ?>
Basically, we have no choice… we will always be served a chicken taco. However, the same expression could be stated using the apply_filters() function. It is like ordering a taco and having the server ask you “well what kind of taco would you like?”
<?php $taco = apply_filters( 'get_taco', 'chicken' ); ?>
The above code gives us access to the type of taco that we would like to have served. We can create a function which hooks into WordPress an changes the default value of$taco
.
<?php add_filter( 'get_taco', 'my_special_order' ); function my_special_order( $content ) { return 'shredded beef'; } ?>
By adding the above code to you theme’s functions.php file or to a custom plugin, you are able to change the value of the variable $taco
to whatever you like. Notice that the function “my_special_order” accepts one value. In this situation the value of$content
is equal to the value of the second argument passed to the apply_filters() function. In this example it would be “chicken”.
<?php add_filter( 'get_taco', 'my_special_order' ); function my_special_order( $content ) { return $content . ' and avocado'; } ?>
The above code appends a string to the end of “chicken” resulting in a value of “chicken and avocado”.
what would be a good example of correctly using filters while actions would be inappropriate for the situation?
Basically, there usually is no choice for a plugin or theme developer as to which method they can use. The WordPress core is filled with calls to apply_filters() anddo_action(). If I need to change the value of a piece of data, I will search through the core until I locate the file where that data is defined and see if it is possible to filter it’s value.
If I need to do something at a certain time, I will look for calls to the do_action() hook. A simple example would be if I wanted to print custom css to the head of the document. I could easily add the following code to my theme’s functions.php file:
<?php add_action( 'wp_head', 'print_my_custom_scripts' ); function print_my_custom_scripts(){ print '<style type="text/css">.red{color:#f00;}</style>'; } ?>
Notice how this time, the function did not return a value – it did something -> it printed text to the browser.
Filters change data while actions allow us to do stuff.
when should I use an action and when a filter?
You would want to use an action where you need to do something at a certain point in time… add options to the database or print css or javascript.
You should use a filter where you would want to alter the value of some data that WordPress has passed through the apply_filters() function.
do the ‘hooks’ for actions and filters overlap? -can I add a either a filter or an action to the same hook?
Actually, both filters and actions are hooks. That being said, the answer is “no”.
http://wordpress.org/support/topic/fliters-vs-actions-from-a-newbe
Formato em português da hora e data no WordPress
Tutorial do formato em português da hora e data no WordPress
Sem muita enrolação vou explicar nesse tutorial quais são os formatos de hora aceitos no WordPress que segue o padrão do PHP e dar alguns exemplos para facilitar a vida das pessoas que, como eu, se enrolaram todas para conseguir informação tão simples.
Data
d – Dia do mês, 2 dígitos com zero
D – Apresentação em texto do dia com três letras
j – Dia do mês sem zero
l (letra L minúscula) – Apresentação por extenso do dia da semanarepresentation
F – Apresentação por extenso do dia do mês
m – Apresentação numérica do mês, com zero
M – Apresentação abreviada do mês com três letras
n – Apresentação numérica do mês, sem zero
Y – Apresentação completa do ano, com quatro dígitos
y – Apresentação curta do ano, com dois dígitos
Hora
a – Mostra am/pm em letras minúsculas
A – Mostra AM/PM em letras maiúsculas
g – Formato 12 horas sem zeros
G – Formato 24 horas sem zeros
h – Formato 12 horas com zeros
H – Formato 24 horas com zeros
i – Minutos com zeros
s – Segundos com zeros
Para alterar a forma como a data e hora são exibidas no seu blog, no menu da administração, clique em “Opções”, depois em “Geral”.
Procure uma caixa chamada “Formato de hora predefinido” e coloque sua formatação, conforme seu gosto.
Após clique no botão “Atualizar Opções” no final da página.
Bom, no meu caso essa explicação não funcionou!
Tive que alterar diretamente nos arquivos archive.php, index.php e single.php.
Localizei a linha com o codigo abaixo:
<”?php the_time(…”>
dependendo do layout, o código pode variar e substituí por este:
<?php the_time(__(‘j \d\e F \d\e Y’, ‘kubrick’)) ?>
deixando o formato assim: 20 de abril de 2009.
Alguns exemplos de data:
D d M Y – esta formação resulta em: Dom 18 Nov 2007
l d F Y – esta formação resulta em: Domingo 18 Novembro 2007
j \d\e F \d\e Y – esta formatação resulta em: 18 de Novembro de 2007
d/m/Y – esta formação resulta em: 18/11/2007
d-m-Y – esta formação resulta em: 18-11-2007
Alguns exemplos de hora:
g:i a – esta formação resulta em: 8:30 am
h:i a – esta formação resulta em: 08:30 am
g-i A – esta formação resulta em: 8-30 AM
Créditos: radboxdocs
Publicado em 20 de abril de 2009. Autor do artigo: Denis F. Moreia
Destaques nos posts/pages
Muito útil para para atribuir características diferenciadas a um post qualquer. Ex: marcar um post como “Destaque”
Neste caso vamos adicionar um box com alguns radios abaixo da caixa do editor de texto do wordpress.
PARTE 1
Supondo que colocamos o código num arquivo “/lib/destaques.php” será preciso dar carga no mesmo, incluindo uma linha no arquivo “functions.php” do seu tema. A linha será
“require_once(STYLESHEETPATH.’/lib/destaques.php’);”
O código abaixo cuida do box.
add_action(‘admin_menu’, ‘rpbr_add_inpost_box_destaque’);
function rpbr_add_inpost_box_destaque() {
add_meta_box(‘rpbr_inpost_box_destaque_page‘, ‘Destaque da página inicial‘, ‘rpbr_inpost_box_destaque‘, ‘page‘, ‘normal’, ‘high’);
add_meta_box(‘rpbr_inpost_box_destaque_post‘, ‘Destaque da página inicial‘, ‘rpbr_inpost_box_destaque‘, ‘post‘, ‘normal’, ‘high’);
}
O próximo código cuida da criação do conteúdo dos boxs, ou seja, cria os radios.
function rpbr_inpost_box_destaque() { ?>
<?php wp_nonce_field( plugin_basename(__FILE__), ‘rpbr_inpost_destaque_nonce’ ); ?>
<?php $_rpbr_destaque = rpbr_get_custom_field(‘_rpbr_destaque’); ?>
<br style=”clear: both;” />
<input type=”radio” name=“_rpbr_destaque” id=”rpbr_destaque” value=”ok_principal” <?php checked(‘ok_principal’, rpbr_get_custom_field(‘_rpbr_destaque’));?> />Destaque Principal
<input type=”radio” name=”_rpbr_destaque” id=”rpbr_destaque” value=”ok” <?php checked(‘ok’, rpbr_get_custom_field(‘_rpbr_destaque’));?> />Destaque Menor
<input type=”radio” name=”_rpbr_destaque” id=”rpbr_destaque” value=”” <?php checked(”, rpbr_get_custom_field(‘_rpbr_destaque’));?> />Nenhum Destaque
<br style=”clear: both;” />
<?php
}
Para terminar, uma ação que salva o radio selecionado, sempre que a página/post for salvo.
add_action(‘save_post’, ‘rpbr_inpost_destaque_save‘, 1, 2);
function rpbr_inpost_destaque_save($post_id, $post) {// verify the nonce
if ( !isset($_POST[‘rpbr_inpost_destaque_nonce’]) || !wp_verify_nonce( $_POST[‘rpbr_inpost_destaque_nonce’], plugin_basename(__FILE__) ) )
return $post->ID;// don’t try to save the data under autosave, ajax, or future post.
if ( defined(‘DOING_AUTOSAVE’) && DOING_AUTOSAVE ) return;
if ( defined(‘DOING_AJAX’) && DOING_AJAX ) return;
if ( defined(‘DOING_CRON’) && DOING_CRON ) return;// is the user allowed to edit the post or page?
if ( (‘page’ == $_POST[‘post_type’] && !current_user_can(‘edit_page’, $post->ID)) || !current_user_can(‘edit_post’, $post->ID ) )
return $post->ID;$rpbr_destaque_value = $_POST[‘_rpbr_destaque‘];
if ( $rpbr_destaque_value ) {
// save/update
update_post_meta($post_id, ‘_rpbr_destaque‘, $rpbr_destaque_value);
} else {
// delete if blank
delete_post_meta($post_id, ‘_rpbr_destaque‘);
}}
FIM DA PRIMEIRA PARTE
PARTE 2
A parte 2 diz respeito a exibição das publicações marcadas como destaque.
O valor do radio selecionado é gravado como uma meta_key do post/page.
Desta forma é possível filtrar consultas.
O código abaixo pega a última publicação marcada como destaque principal:
$args = array(‘post_type’ => ‘any’,
‘showposts’ => 1,
‘orderby’=>’date’,
‘meta_key’=>’_rpbr_destaque‘,
‘meta_value’=>’ok_principal‘,
‘post_status’ => ‘publish’,
‘post__not_in’ => get_option( ‘sticky_posts’ ));
$recent = new WP_Query($args);
O código abaixo pega as últimas 6 publicações marcadas como destaque:
$args = array (
‘post_type’ => ‘any’,’
showposts’ => 6,
‘orderby’=>’date’,
‘meta_key’=>‘_rpbr_destaque’,
‘meta_value’=>’ok‘,
‘post_status’ => ‘publish’,
‘post__not_in’ => get_option( ‘sticky_posts’ ));
$recent = new WP_Query($args);
PASSO 3
No caso acima, o destaque principal pode aparecer no post associado a uma imagem. Neste caso, é interessante adicionar ao function.php do seu tema, o seguinte:
add_image_size( ‘destaque-principal’, 340, 230 );//destaque principal, home
Para finalizar, no corpo da página onde a chamada ao destaque principal será exibida, você coloca:
<div>
<?php if ( has_post_thumbnail() ) { ?> <a href=”<?php the_permalink(); ?>”><?php the_post_thumbnail( ‘destaque-principal’ ); ?></a> <?php } ?>
</div>
FUNÇÕES ÚTEIS
function rpbr_custom_field($field) {
echo rpbr_get_custom_field($field);
}
function rpbr_get_custom_field($field) {
global $post;if ( null === $post ) return FALSE;
$custom_field = get_post_meta($post->ID, $field, true);
if ( $custom_field ) {
// sanitize and return the value of the custom field
return wp_kses_stripslashes( wp_kses_decode_entities( $custom_field ) );
}
else {
// return FALSE if custom field is empty
return FALSE;
}
}
10 Useful WordPress Security Tweaks
http://www.smashingmagazine.com/2010/07/01/10-useful-wordpress-security-tweaks/
By Jean-Baptiste Jung
Security has always been a hot topic. Offline, people buy wired homes, car alarms and gadgets to bring their security to the max. Online, security is important, too, especially for people who make a living from websites and blogs. In this article, we’ll show you some useful tweaks to protect your WordPress-powered blog.
1. Prevent Unnecessary Info From Being Displayed
The problem
When you fail to log into a WordPress blog, the CMS displays some info telling you what went wrong. This is good if you’ve forgotten your password, but it might also be good for people who want to hack your blog. So, why not prevent WordPress from displaying error messages on failed log-ins?
The solution
To remove log-in error messages, simply open your theme’s functions.php file, and paste the following code:
1 |
add_filter( 'login_errors' ,create_function( '$a' , "return null;" )); |
Save the file, and see for yourself: no more messages are displayed if you fail to log in.
Please note that there are several functions.php files. Be sure to change the one in your wp-content directory.
Code explanation
With this code, we’ve added a simple hook to overwrite the login_errors()
function. Because the custom function that we created returns only null
, the message displayed will be a blank string.
Source
2. Force SSL Usage
The problem
If you worry about your data being intercepted, then you could definitely use SSL. In case you don’t know what it is, SSL is a cryptographic protocol that secures communications over networks such as the Internet.
Did you know that forcing WordPress to use SSL is possible? Not all hosting services allow you to use SSL, but if you’re hosted on Wp WebHost4 or HostGator5, then SSL is enabled.
The solution
Once you’ve checked that your Web server can handle SSL, simply open your wp-config.php file (located at the root of your WordPress installation), and paste the following:
1 |
define( 'FORCE_SSL_ADMIN' , true); |
Save the file, and you’re done!
Code explanation
Nothing hard here. WordPress uses a lot of constants to configure the software. In this case, we have simply defined the FORCE_SSL_ADMIN
constant and set its value to true
. This results in WordPress using SSL.
Source
3. Use .htaccess To Protect The wp-config File
The problem
As a WordPress user, you probably know how important the wp-config.php file is. This file contains all of the information required to access your precious database: username, password, server name and so on. Protecting the wp-config.php file is critical, so how about exploiting the power of Apache to this end?
The solution
The .htaccess file is located at the root your WordPress installation. After creating a back-up of it (it’s such a critical file that we should always have a safe copy), open it up, and paste the following code:
1 |
<files wp-config.php> |
2 |
order allow,deny |
3 |
deny from all |
4 |
</files> |
Code explanation
.htaccess files are powerful and one of the best tools to prevent unwanted access to your files. In this code, we have simply created a rule that prevents any access to the wp-admin.php file, thus ensuring that no evil bots can access it.
Source
4. Blacklist Undesired Users And Bots
The problem
This is as true online as it is in real life: someone who pesters you today will probably pester you again tomorrow. Have you noticed how many spam bots return to your blog 10 times a day to post their annoying comments? The solution to this problem is quite simple: forbid them access to your blog.
The solution
Paste the following code in your .htaccess file, located at the root of your WordPress installation. As I said, always back up the .htaccess file before editing it. Also, don’t forget to change 123.456.789
to the IP address you want to ban.
1 |
<Limit GET POST PUT> |
2 |
order allow,deny |
3 |
allow from all |
4 |
deny from 123.456.789 |
5 |
</LIMIT> |
Code explanation
Apache is powerful and can easily be used to ban undesirable people and bots from your website. With this code, we’re telling Apache that everyone is allowed to visit our blog except the person with the IP address 123.456.789
.
To ban more people, simply repeat line 4 of this code on a new line, using another IP address, as shown below:
1 |
<Limit GET POST PUT> |
2 |
order allow,deny |
3 |
allow from all |
4 |
deny from 123.456.789 |
5 |
deny from 93.121.788 |
6 |
deny from 223.956.789 |
7 |
deny from 128.456.780 |
8 |
</LIMIT> |
Source
5. Protect Your WordPress Blog From Script Injections
The problem
Protecting dynamic websites is especially important. Most developers always protect their GET
and POST
requests, but sometimes this is not enough. We should also protect our blog against script injections and any attempt to modify the PHP GLOBALS
and _REQUEST
variables.
The solution
The following code blocks script injections and any attempts to modify the PHP GLOBALS
and _REQUEST
variables. Paste it in your .htaccess file (located in the root of your WordPress installation). Make sure to always back up the .htaccess file before modifying it.
1 |
Options +FollowSymLinks |
2 |
RewriteEngine On |
3 |
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR] |
4 |
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR] |
5 |
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2}) |
6 |
RewriteRule ^(.*)$ index.php [F,L] |
Code explanation
Using the power of the .htaccess file, we can check requests. What we’ve done here is check whether the request contains a <script> and whether it has tried to modify the value of the PHP GLOBALS
or _REQUEST
variables. If any of these conditions are met, the request is blocked and a 403 error is returned to the client’s browser.
Sources
6. Fight Back Against Content Scrapers
The problem
If your blog is the least bit known, people will no doubt try to use your content on their own websites without your consent. One of the biggest problems is hot-linking to your images, which saps your server’s bandwidth.
The solution
To protect your website against hot-linking and content scrapers, simply paste the following code in your .htaccess file. As always, don’t forget to back up when modifying the .htaccess file.
1 |
RewriteEngine On |
2 |
#Replace ?mysite\.com/ with your blog url |
3 |
RewriteCond %{HTTP_REFERER} !^http: //(.+\.)?mysite\.com/ [NC] |
4 |
RewriteCond %{HTTP_REFERER} !^$ |
5 |
#Replace /images/nohotlink.jpg with your "don't hotlink" image url |
6 |
RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L] |
Once you’ve saved the file, only your website will be able to link to your images, or, to be more correct, no one would link to your images, because it would be way too complicated and time-consuming. Other websites will automatically display the nohotlink.jpg image. Note that you can also specify a non-existent image, so websites that try to hot-link to you would display a blank space.
Code explanation
With this code, the first thing we’ve done is check the referrer to see that it matches our blog’s URL and it is not empty. If it doesn’t, and the file has a JPG, GIF, BMP or PNG extension, then the nohotlink image is displayed instead.
Source
7. Create A Plug-In To Protect Your Blog From Malicious URL Requests
The problem
Hackers and evil-doers often use malicious queries to find and attack a blog’s weak spots. WordPress has good default protection, but enhancing it is possible.
The solution
Paste the following code in a text file, and save it as blockbadqueries.php. Once you’ve done that, upload it to your wp-content/plugins
directory and activate it as you would any other plug-in. Now your blog is protected against malicious queries.
01 |
<?php |
02 |
/* |
03 |
Plugin Name: Block Bad Queries |
04 |
Plugin URI: http://perishablepress.com/press/2009/12/22/protect-wordpress-against-malicious-url-requests/ |
05 |
Description: Protect WordPress Against Malicious URL Requests |
06 |
Author URI: http://perishablepress.com/ |
07 |
Author: Perishable Press |
08 |
Version: 1.0 |
09 |
*/ |
10 |
11 |
global $user_ID ; |
12 |
13 |
if ( $user_ID ) { |
14 |
if (!current_user_can( 'level_10' )) { |
15 |
if ( strlen ( $_SERVER [ 'REQUEST_URI' ]) > 255 || |
16 |
strpos ( $_SERVER [ 'REQUEST_URI' ], "eval(" ) || |
17 |
strpos ( $_SERVER [ 'REQUEST_URI' ], "CONCAT" ) || |
18 |
strpos ( $_SERVER [ 'REQUEST_URI' ], "UNION+SELECT" ) || |
19 |
strpos ( $_SERVER [ 'REQUEST_URI' ], "base64" )) { |
20 |
@header( "HTTP/1.1 414 Request-URI Too Long" ); |
21 |
@header( "Status: 414 Request-URI Too Long" ); |
22 |
@header( "Connection: Close" ); |
23 |
@ exit ; |
24 |
} |
25 |
} |
26 |
} |
27 |
?> |
Code explanation
What this code does is pretty simple. It checks for excessively long request strings (more than 255 characters) and for the presence of either the eval
or base64
PHP functions in the URI. If one of these conditions is met, then the plug-in sends a 414 error to the client’s browser.
Source
8. Remove Your WordPress Version Number… Seriously!
The problem
As you may know, WordPress automatically displays the version you are using in the head of your blog files. This is pretty harmless if your blog is always up to date with the latest version (which is certainly what you should be doing anyway). But if for some reason your blog isn’t up to date, WordPress still displays it, and hackers will learn this vital piece of information.
The solution
Paste the following line of code in the functions.php file of your theme. Save it, refresh your blog, and voila: no more WordPress version number in the header.
1 |
remove_action( 'wp_head' , 'wp_generator' ); |
Code explanation
To execute certain actions, WordPress uses a mechanism called “hooks,” which allow you to hook one function to another. The wp_generator
function, which displays the WordPress version, is hooked. We can remove this hook and prevent it from executing by using the remove_action()
function.
Source
9. Change The Default “Admin” Username
The problem
Brute force is one of the easiest ways to break a password. The method is simple: try as many different passwords as possible until the right one is found. Users of the brute force method use dictionaries, which give them a lot of password combinations.
But knowing your username certainly makes it easier for them to guess the right combination. This is why you should always change the default “admin” username to something harder to guess.
Note that WordPress 3.0 let you choose your desired username by default. Therefore, this tip is still usefull if you still use the old “admin” account from older WordPress versions.
The solution
If you haven’t changed the “admin” username yet, simply run the following SQL query to your database to change it for good. Don’t forget to specify your desired username.
1 |
UPDATE wp_users SET user_login = 'Your New Username' WHERE user_login = 'Admin' ; |
Code explanation
Usernames are stored in the database. To change one, a simple UPDATE
query is enough. Note that this query will not transfer posts written by “admin” to your new username; the source post below shows you how to easily do that.
Source
10. Prevent Directory Browsing
The problem
By default, most hosts allow directory listing. So, if you type www.yourblog.com/wp-includes
in the browser’s address bar, you’ll see all of the files in that directory. This is definitely a security risk, because a hacker could see the last time that files were modified and access them.
The solution (Updated)
Just add the following to the Apache configuration or your .htaccess file:
1 |
Options -Indexes |
Code explanation
Please note that it’s not enough to update the blog’s robots.txt file with Disallow: /wp*
. This would prevent the wp-directory from being indexed, but will not prevent users from seeing it.
Source
(al)
10 ótimos shortcodes para WordPress
CTRL+C,CTRL+V from http://imasters.com.br/artigo/15146/wordpress/10_otimos_shortcodes_para_wordpress
Os shortcodes do WordPress foram introduzidos na versão 2.5. Estes códigos são uma forma muito simples de ‘puxar’ a informação desejada, recorrendo a poucas linhas de código. Neste artigo, vou mostrar-lhe os 10 shortcodes mais incríveis para WordPress, que você poderá começar a utilizar imediatamente no seu blog!
01. Apresentar artigos relacionados
Os artigos relacionados são uma forma muito eficiente de manter os leitores por mais tempo no seu blog, ocupados com a visitação de novas páginas constantemente. Isso aumenta o número de páginas vistas gradualmente, ao mesmo tempo que aumenta o potencial de rentabilidade do seu blog. Existem dezenas de plugins para executar esta função, mas por que não utilizar um shortcode que o faça automaticamente?
function related_posts_shortcode( $atts ) {
extract(shortcode_atts(array(
'limit' => '5,
), $atts));
global $wpdb, $post, $table_prefix;
if ($post->ID) {
$retval = '<ul>';
// Get tags
$tags = wp_get_post_tags($post->ID);
$tagsarray = array();
foreach ($tags as $tag) {
$tagsarray[] = $tag->term_id;
}
$tagslist = implode(',', $tagsarray);
// Do the query
$q = "SELECT p.*, count(tr.object_id) as count
FROM $wpdb->term_taxonomy AS tt, $wpdb->term_relationships AS tr, $wpdb->posts AS p WHERE tt.taxonomy ='post_tag' AND tt.term_taxonomy_id = tr.term_taxonomy_id AND tr.object_id = p.ID AND tt.term_id IN ($tagslist) AND p.ID != $post->ID
AND p.post_status = 'publish'
AND p.post_date_gmt < NOW()
GROUP BY tr.object_id
ORDER BY count DESC, p.post_date_gmt DESC
LIMIT $limit;";
$related = $wpdb->get_results($q);
if ( $related ) {
foreach($related as $r) {
$retval .= '<li><a title="'.wptexturize($r->post_title).'" href="'.get_permalink($r->ID).'">'.wptexturize($r->post_title).'</a></li>';
}
} else {
$retval .= '
<li>Nenhum artigo relacionado encontrado</li>';
}
$retval .= '</ul>';
return $retval;
}
return;
}
add_shortcode('related_posts', 'related_posts_shortcode');
Código de utilização:
[related_posts]
02. Apresentar um gráfico Google
A Google Chart API é, provavelmente, a ferramenta mais interessante da internet para apresentar gráficos dinâmicos em páginas e blogs. Aqui fica um shortcode para tornar essa utilização ainda mais simples no seu blog WordPress:
function chart_shortcode( $atts ) {
extract(shortcode_atts(array(
'data' => ",
'colors' => ",
'size' => '400×200,
'bg' => 'ffffff',
'title' => ",
'labels' => ",
'advanced' => ",
'type' => 'pie'
), $atts));
switch ($type) {
case 'line' :
$charttype = 'lc'; break;
case 'xyline' :
$charttype = 'lxy'; break;
case 'sparkline' :
$charttype = 'ls'; break;
case 'meter' :
$charttype = 'gom'; break;
case 'scatter' :
$charttype = 's'; break;
case 'venn' :
$charttype = 'v'; break;
case 'pie' :
$charttype = 'p3; break;
case 'pie2d' :
$charttype = 'p'; break;
default :
$charttype = $type;
break;
}
if ($title) $string .= '&chtt='.$title.";
if ($labels) $string .= '&chl='.$labels.";
if ($colors) $string .= '&chco='.$colors.";
$string .= '&chs='.$size.";
$string .= '&chd=t:'.$data.";
$string .= '&chf='.$bg.";
return '<img title="'.$title.'" src="http://chart.apis.google.com/chart?cht='.$charttype.".$string.$advanced.'" alt="'.$title.'" />';
}
add_shortcode('chart', 'chart_shortcode');
Código de utilização:
[chart data="41.52,37.79,20.67,0.03" bg="F7F9FA" labels="Reffering+sites|Search+Engines|Direct+traffic|Other" colors="058DC7,50B432,ED561B,EDEF00" size="488x200" title="Traffic Sources" type="pie"]
03. Integrar anúncios no AdSense
O Adsense é, provavelmente, a forma mais simples e eficaz de rentabilizar um website ou um blog. Utilizando widgets, é relativamente simples colocar anúncios Adsense no seu blog. No entanto, a melhor forma de rentabilizar um blog é, seguramente, utilizando Adsense dentro dos seus posts. Este processo torna-se extremamente simples e mágico, recorrendo aos shortcodes para WordPress. Vejamos:
function showads() {
return '<script type="text/javascript"><!
google_ad_client = "pub-3637220125174754;
google_ad_slot = "4668915978;
google_ad_width = 468;
google_ad_height = 60;
//>
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
';
}
add_shortcode('adsense', 'showads');
Código de utilização:
[adsense]
04. Mostrar conteúdo privado para membros premium
Cada vez mais os blog e blogueiros adotam os chamados ‘conteúdos premium’, onde determinados grupos de usuários têm de pagar para ter acesso a conteúdos privilegiados. Sabe como apresentar conteúdos premium apenas para os seus ‘usuários premium’? Utilize este shortcode:
function access_check_shortcode( $attr, $content = null ) {
extract( shortcode_atts( array( 'capability' => 'read' ), $attr ) );
if ( current_user_can( $capability ) && !is_null( $content ) && !is_feed() )
return $content;
return 'Desculpe, apenas membros registados podem ter acesso a estes conteúdos.';
}
add_shortcode( 'access', 'access_check_shortcode' );
Código de utilização:
[access capability="switch_themes"]
05. Como integrar seus conteúdos de RSS feed
Entre outras coisas fantásticas, o WordPress tem um leitor de RSS Feeds integrado no seu código, que possibilita a leitura dos feeds no painel de controle do blog wordpress. No entanto, recorrendo a um shortcode, é possível colocar esses mesmos RSS Feeds onde você desejar, incluindo nos seus posts.
//This file is needed to be able to use the wp_rss() function.
include_once(ABSPATH.WPINC.'/rss.php');
function readRss($atts) {
extract(shortcode_atts(array(
"feed" => 'http://',
"num" => '1,
), $atts));
return wp_rss($feed, $num);
}
add_shortcode('rss', 'readRss');
Código de utilização:
- Ocorreu um erro. É provável que o feed esteja indisponível. Tente mais tarde.
06. Encurtar um endereço URL para o twitter
Uma das vantagens que o Twitter tem é de utilizar no seu código o core da TinyURL para encurtar os endereços URL presentes nos posts dos seus usuários. No entanto, é possível facilitar a vida dos leitores com um shortcut que faça isso automaticamente:
function subzane_shorturl($atts) {
extract(shortcode_atts(array(
'url' => ",
'name' => ",
), $atts));
$request = 'http://u.nu/unu-api-simple?url=' . urlencode($url);
$short_url = file_get_contents($request);
if (substr($short_url, 0, 4) == 'http') {
$name = empty($name)?$short_url:$name;
return '<a href="'.$short_url.'">'.$name.'</a>';
} else {
$name = empty($name)?$url:$name;
return '<a href="'.$url.'">'.$name.'</a>';
}
}
add_shortcode('shorturl', 'subzane_shorturl');
Código de utilização:
[shorturl name="shortcode" url="http://codex.wordpress.org/Shortcode_API"]
07. Apresente a última imagem anexada a um post
Em vez de utilizar custom fields ou endereços URL para puxar as imagens anexadas aos seus posts, por que não recorrer a um shortcode que o faça automaticamente?
function sc_postimage($atts, $content = null) {
extract(shortcode_atts(array(
"size" => 'thumbnail',
"float" => 'none'
), $atts));
$images =& get_children( 'post_type=attachment&post_mime_type=image&post_parent=' . get_the_id() );
foreach( $images as $imageID => $imagePost )
$fullimage = wp_get_attachment_image($imageID, $size, false);
$imagedata = wp_get_attachment_image_src($imageID, $size, false);
$width = ($imagedata[1]+2);
$height = ($imagedata[2]+2);
return '<div style="width: '.$width.'px; height: '.$height.'px; float: '.$float.';">'.$fullimage.'</div>';
}
add_shortcode("postimage", "sc_postimage");
Código de utilização:
[postimage]
8. Adicione notas administrativas aos seus posts
Quando se trabalha com blogs multi-editor, é extremamente importante notificar outros escritores de problemas que existam nos seus posts. E se pudesse adicionar notas a esses mesmos posts, que só pudessem ser lidas por outros administradores? Nada como usar um shortcode para resolver esse problema:
add_shortcode( 'note', 'sc_note' );
function sc_note( $atts, $content = null ) {
if ( current_user_can( 'publish_posts' ) )
return '<div>'.$content.'</div>';
return ";
}
Código de utilização:
[note]Esta é uma nota pessoal que só pode ser lida por administradores![/note]
09. Remova a formatação automática do WordPress
Se você é um programador ou desenvolvedor, e costuma colocar porções de código no seu blog WordPress, provavelmente já reparou que a formatação automática do WordPress pode ser um verdadeiro problema. No entanto, existe um shortcode que o ajuda a resolver esse problema em determinadas porções de texto. Vejamos:
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);
Código de utilização:
[raw]Esta porção de texto não será formatada automaticamente pelo WP.[/raw]
10. Apresente as estatísticas do seu blog com shortcodes
Sempre gostou da possibilidade de mostrar as estatísticas do seu blog em tempo real? Graças ao Wesley e ao seu plugin “Blog Stats”, é possível apresentar de forma dinâmica, e através de shortcodes, todas as estatísticas do seu blog. Faça download do plugin Blog Stats e, depois de instalado, utilize os seguintes shortcodes:
[pagerank]
[feedburner_subscribers]
[alexa_rank]
[technorati_authority]
[technorati_rank]
[user_count]
[post_count]
[page_count]
[comment_count]
[trackback_count]
[avg_comments_per_post]
[category_count]
[tag_count]
[link_count]
[google_backlinks]
[yahoo_backlinks]
[delicious_bookmarks]
Até a próxima!!
10 Useful WordPress Search Code Snippets
Post Ctrl+C,Ctrl+V from http://speckyboy.com/2010/09/19/10-useful-wordpress-search-code-snippets/
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 |
} |
7 |
8 |
add_filter( 'pre_get_posts' , 'SearchFilter' ); |
Source: wprecipes.com →
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: www.melandri.net →
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: wpgarage.com →
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 |
} |
08 |
09 |
// This filter will jump into the loop and arrange our results before they're returned |
10 |
add_filter( 'pre_get_posts' , 'SearchFilter' ); |
Source: ashbluewebdesign.com →
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( ' — ' ); echo $count . ' ' ; _e( 'articles' ); wp_reset_query(); ?></h2> |
Source: problogdesign.com →
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()); |
03 |
04 |
if ( strlen ( $query ) > 0){ |
05 |
echo ' |
06 |
<script type= "text/javascript" > |
07 |
var hls_query = "'.$query.'" ; |
08 |
</script> |
09 |
'; |
10 |
} |
11 |
} |
12 |
13 |
function hls_init_jquery() { |
14 |
wp_enqueue_script( 'jquery' ); |
15 |
} |
16 |
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: weblogtoolscollection.com →
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 ) { |
02 |
03 |
if ( is_search() ) { |
04 |
$query ->is_search = false; |
05 |
$query ->query_vars[s] = false; |
06 |
$query ->query[s] = false; |
07 |
08 |
// to error |
09 |
if ( $error == true ) |
10 |
$query ->is_404 = true; |
11 |
} |
12 |
} |
13 |
14 |
add_action( 'parse_query' , 'fb_filter_query' ); |
15 |
add_filter( 'get_search_form' , create_function( '$a' , "return null;" ) ); |
Source: wpengineer.com →
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: wphacks.com →
Implement Google AJAX Search API
Implement 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 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
Google 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 →
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’) ) {
update_right_now_message();
}
===============================================================
http://wordpress.org/extend/plugins/hide-update-reminder/
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.
15 fantásticos comandos SQL para WordPress
Você encontra este artigo, mais bonito e organizado, e quem sabe até mais atualizado em: http://desenvolvimentoparaweb.com/wordpress/15-comandos-sql-wordpress/
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!
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.
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, 'http://www.enderecoantigo.com', 'http://www.endereconovo.com') 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, 'http://www.enderecoantigo.com', 'http://www.endereconovo.com');
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, 'http://www.enderecoantigo.com', 'http://www.endereconovo.com');
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="http://www.enderecoantigo.com', 'src="http://www.endereconovo.com');
Também é preciso atualizar o GUID para o tipo “attachment” com a seguinte instrução SQL:
UPDATE wp_posts SET guid = REPLACE (guid, 'http://www.enderecoantigo.com', 'http://www.endereconovo.com') 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, 'http://www.enderecoantigo.com','http://www.endereconovo.com');
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;