Converting keywords in posts on the fly

(Adam Capriola) #1

What I’d like to do is convert keywords within posts to links.

Here are a few posts for reference:

These examples use postProcessText and inlineRegexp for altering the text. Is there a way to alter the text on the fly, rather than storing the manipulated version?

The reason I’d like to change the text as it’s generated is because later I might want to stop linking the keyword. Or I might want existing posts with keywords to be targeted too. Neither of those options is possible with the references above.

(Kane York) #2

I’m not quite sure what you’re saying – if you’re talking about storing the baked HTML, you can run a global rebake after changing the linking.

(Adam Capriola) #3

In WordPress what I do is something like this:

add_filter( 'the_content', 'my_filter' );

function my_filter( $content ) {

	$search = $replace = array();

	// list of terms to search and replace would be here

	$content = preg_replace( $search, $replace, $content );

	return $content;


All terms in all past, present, and future posts are targeted, and if I comment out the add_filter line, the terms would revert back to normal. Is that same kind of functionality achievable with the examples above?

To me it seemed like only new posts with the terms were being affected and there was no way to alter terms that had already been replaced. I’m not all that familiar with “baking” and “rebaking.”

(Kane York) #4

Maybe you want to run some JS on every post in the browser…?

(Adam Capriola) #5

I tried adding a JS file to a static HTML page a while back for search/replace purposes, but the problem is I have quite an extensive list of keywords I’d like to target, so performance will be noticeably bad.

Being able to do the search/replace before the posts are displayed in the browser is optimal.

(Salman, Freelance Developer) #6

I’m not familiar with WP but it seems like WP is doing this text processing on the fly as oppose to doing it only when the post is created/updated.

If you want the ability to change things on the fly, JS might be the best option or you would have to customize Discourse to do it on the fly (which isn’t going to be a good idea for performance reasons). The other option is to re-bake all the posts when your list changes, which again might not be a good idea if your list changes frequently.

(Adam Capriola) #7

After playing around with the new “Rebuild HTML” for a single post feature, it appears baking is actually perfect for my situation. (I didn’t understand how it worked - sorry!) If I change terms, all that’s needed is a rebake.

@riking how would I run a global rebake?

(Kane York) #8

Log into the container and run rake posts:rebake.

cd /var/discourse
./launcher enter app
rake posts:rebake
# wait

(Dan Dascalescu) #9

A global rebake might needlessly process all posts. You can use the API to target only specified post id(s):