usama sulaiman
usama sulaiman

Reputation: 2019

Wordpress: How to add_filter to a special div of the_content

I'm trying to add a filter to only a special div of my wordpress content

sure my plugin code now will effect to all the post content, but what i need is to apply it only for a special div class="game_req" not the other divs ex. the div class="how_to_play"

my post structure:

<div>
    ..........
    <div class="game_req"> <!-- i need to apply filter to only this div -->
         - ball : is a round ..........
         - key : is what we need to ..........
         - caw : is an animal ..........
    </div>
    <div class="how_to_play">
         1- use the key to open .......
         2- use ball to ........
         3- use caw to .........
    </div>
    <div class="sss">
         .... key .......
         .... ball to ........
         .... caw .........
    </div>
    ..........
</div>

my plugin filter:

function myReplace_function($content){

$patterns = array(
    '/\bball\b/',
    '/\bkey\b/',
    '/\bcaw\b/'
);

$replacements = array(
    'ball ( <img src="smallImgs/ball.png" alt="ball"/> )',
    'key ( <img src="smallImgs/key.png" alt="key"/> )',
    'caw ( <img src="smallImgs/caw.png" alt="caw"/> )'
);

return preg_replace($patterns,$replacements,$content);

}
add_filter('the_content','myReplace_function');

Upvotes: 2

Views: 2223

Answers (1)

usama sulaiman
usama sulaiman

Reputation: 2019

Because no one answered my question, so I decided to try many ways to fix my problem on my own

finally the solution is:

I shouldn't use a add_filter , instead I have to use add_shortcode the changes only is replace

 function myReplace_function($content){

with

 function myReplace_function($attrs,$content=none){

also adding any specific code to be as shortcode ex. my_shortcode instead of the_content

so my function should looks like this

function myReplace_function($attrs,$content=none){

$patterns = array(
    '/\bball\b/',
    '/\bkey\b/',
    '/\bcaw\b/'
);

$replacements = array(
    'ball ( <img src="smallImgs/ball.png" alt="ball"/> )',
    'key ( <img src="smallImgs/key.png" alt="key"/> )',
    'caw ( <img src="smallImgs/caw.png" alt="caw"/> )'
);

return preg_replace($patterns,$replacements,$content);

}
add_shortcode('my_shortcode','myReplace_function');

finally I can use it by wrapping any part of my post content [my_shortcode]...[/my_shortcode]

so if I apply that to my question example it will be like below:

[my_shortcode]<div class="game_req"> <!-- i need to apply filter to only this div -->
         - ball : is a round ..........
         - key : is what we need to ..........
         - caw : is an animal ..........
</div>[/my_shortcode]

That's all.

Upvotes: 3

Related Questions