WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Passing an argument to add_filter (5 posts)

  1. mmond
    Member
    Posted 3 years ago #

    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

  2. alchymyth
    The Sweeper & Moderator
    Posted 3 years ago #

    try and use return instead of print

  3. mmond
    Member
    Posted 3 years ago #

    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>

  4. mmond
    Member
    Posted 3 years ago #

    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.

  5. bitspan
    Member
    Posted 3 years ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic