- This topic has 3 replies, 2 voices, and was last updated 5 years, 4 months ago by
David.
-
AuthorPosts
-
December 15, 2020 at 6:28 am #1581421
Randy
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!
December 15, 2020 at 8:50 am #1581761David
StaffCustomer SupportHi 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.
December 15, 2020 at 9:31 am #1581803Randy
Ok, thank you. I think that makes sense 🙂
So I can use something like the Snippets plugin to add the add_filter hooks.
December 15, 2020 at 4:05 pm #1582171David
StaffCustomer SupportYep thats correct – they go in Code Snippets or in a Child Theme functions.php
Glad to be of help -
AuthorPosts
- You must be logged in to reply to this topic.