¿Está buscando una manera de reemplazar palabras clave dentro de the_content y the_excerpt utilizando una matriz asociativa? Si bien es probable que haya un plugin para esto, hemos creado un fragmento de código rápido que puede utilizar para reemplazar palabras clave en the_content y the_excerpt en WordPress.
Instrucciones:
Todo lo que tienes que hacer es añadir este código al archivo functions.php de tu tema o en un plugin específico del sitio:
function replace_text_wps($text){ $replace = array( // 'WORD TO REPLACE' => 'REPLACE WORD WITH THIS' 'wordpress' => '<a href="#">wordpress</a>', 'excerpt' => '<a href="#">excerpt</a>', 'function' => '<a href="#">function</a>' ); $text = str_replace(array_keys($replace), $replace, $text); return $text; } add_filter('the_content', 'replace_text_wps'); add_filter('the_excerpt', 'replace_text_wps');
Nota: Si es la primera vez que añade fragmentos de código en WordPress, consulte nuestra guía sobre cómo copiar / pegar correctamente fragmentos de código en WordPress, para no romper accidentalmente su sitio.
Si te ha gustado este fragmento de código, por favor considere revisar nuestros otros artículos en el sitio como: 19 mejores plugins de WordPress para fotógrafos y cómo aumentar el tamaño máximo de carga de archivos en WordPress.
Hello, made an alteration of it like this but can’t get any effect:
function replace_text_wps($text){
$replace = array(
// ‘WORD TO REPLACE’ => ‘REPLACED WITH THIS’
‘spicy’ => ”,
‘veryspicy’ => ”
);
$text = str_replace(array_keys($replace), $replace, $text);
return $text;
}
add_filter(‘the_content’, ‘replace_text_wps’);
I added this in the end of the theme functions.php but I can’t get any effect.
[…] code is courtesy of Kevin Chard from WpSnipp, and we should be thankful to […]
[…] On the code above using add_filter to filter the_content and the_excerpt. So all match words will be replace with the new parameter as described. That’s is, we hope this tutorial works on you. Thanks Kevin Chard from WP Snipp for this code […]
[…] odlomak koda preuzet je sa sajta wpsnipp.com, odli?ne kolekcije PHP caka i trikova za […]
You have to be careful of this if you intend to use those keywords on an image caption, as it seems to break the caption. That’s too much of a drawback for me to use on common keyword, but otherwise this is really great. I’ll certainly find a use for this. Thanks!
Hi Sean, yes this is true it will replace any text, but I’m glad you like the snippet. I’m sure that I will update it in the future to be a little more practical.
If the word already is in a link, it will be some problems. My best, and simplest, solution for that is to replace eg. ‘ wordpress ‘ so that every appearence of wordpress with spaces on each side will be replaces.
Hi Slowmove, this is true and is something people should take into consideration when using this snippet. Thanks for the suggestion this would work great for some instances. I may have to post an updated version in the future.