WordPress.org

Support

Support » Plugins and Hacks » [Resolved] Passing an argument to add_filter

[Resolved] Passing an argument to add_filter

  • Hi folks,

    I’m trying to pass an argument to the add_filter function to display dynamic content in the loop. When I do, the page renders incorrectly with the function’s content displayed at the top of the page, instead of in the post area.

    The code without an argument displays in the post area correctly:

    add_filter('the_content', 'DisplayMe');
    function DisplayMe($argument) {
    	print "The argument will go here: ";
    }

    I’ve checked the add_filter and related docs here.

    ..and this post looks like a helpful solution and it does pass the argument successfully. But now all the data is rendered at the top of the page and not in the post/loop area.

    The code suggested above that does pass argument but renders at top of page:

    add_filter('the_content', DisplayMe('argument'),1);
    function DisplayMe($argument) {
    	print "The argument will go here: ". $argument;
    }

    It seems like I’m missing something easy here. It acts as if I’ve introduced (or omitted) a table tag or some such.

    Any input appreciated!

    Best,
    Mark

Viewing 4 replies - 1 through 4 (of 4 total)
  • Michael

    @alchymyth

    Forum Moderator

    try and use return instead of print

    Thanks but that is to pass the argument out of the function back up. I’m trying to make the code within add_filter aware of parameters I’ve passed down to it so they can be used in the function itself.

    I did try the change and received the error: Warning: call_user_func_array() [function.call-user-func-array]: First argument is expected to be a valid callback, ‘The argument is: argument’ was given in <../filename>

    alchymyth

    Thinking more about your suggestion, I can make this work that way if I go in reverse. If I call a separate function from inside add_filter then I can pull a variable down into the the_content instead of passing it down when I call it.

    add_filter('the_content', display_me);
    
    function display_me() {
    	print "The argument goes here: ". set_argument();
    }
    
    function set_argument() {
    	$argument = "Hello.";
    	return $argument;
    }

    Thanks for your input.

    mmond, this is how I “solved” it:

    $func = create_function(‘$content’, ‘return ‘.$param.’ . $content;’);
    add_filter(“the_content”, $func);

    However, $param needs to be properly escaped for this to work.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘[Resolved] Passing an argument to add_filter’ is closed to new replies.
Skip to toolbar