Archived topic
Changing page content on the fly
3 replies · Started by Randy on December 15, 2020
Hi!
For modifying the content of certain static pages on the fly, can you help me understand the difference between using a GP hook like generate_before_content to modify the content vs using a code snippet like the one below. For example, let's say I want to modify the content of some reusable blocks on the fly.
<?php
/**
* Replace Text in post content
**/
function vr_replace_content($content) {
$find = array('One', 'Two', 'Three'); // The items to replace
$replace = array('Uno', 'Dos', 'Tres'); // Their replacements
$content = str_replace($find, $replace, $content); // $finds strings in the $content to $replace
return $content; // The filtered content
}
add_filter('the_content','vr_replace_content'); // This injects vr_replace_content() into the filter the_content(). The normal output of the_content() is altered by the custom function vr_replace_content()
(Above example copied from https://journalxtra.com/wordpress/snippets/edit-wordpress-page-source-on-the-fly/)
Just trying to understand how to know which approach is better/faster/more stable to use.
Thanks!
Hi there,
Hook Elements simply insert content into the Themes Templates. The Hook you choose defines where it is displayed within a Template:
https://docs.generatepress.com/article/hooks-visual-guide/
And the Display Rules decides which post type or archive it is displayed on.
The Hook Element is an action hook ie. add_action( 'the_hook', 'the_content_function' );
Whereas the code you have is a Filter Hook and is being applied to the Post Content. Which cannot be done with an action hook.
So Hook Elements ( add_action ) are for inserting stuff, and Filter Hooks ( add_filter ) are for changing stuff.
Ok, thank you. I think that makes sense :)
So I can use something like the Snippets plugin to add the add_filter hooks.
Yep thats correct - they go in Code Snippets or in a Child Theme functions.php
Glad to be of help