it appears i have a problem with understanding how add_action,add_filter and apply_filters work.

somewhat abbreviated, i have the following scenario:

in a template file i have this

while ( $the_query->have_posts() ) : $the_query->the_post();
    /*get meta data for this post**/
    $meta=get_post_meta(get_the_ID(), $post_type, true );

        at this stage - amongst other things - print_r($meta) returns
        Array ( [prices] => Array ( [0] => 8 ) )

    /**add add_action hook to change $meta (if possible)**/

        AFTER executing this action I would like to have print_r($meta) return
        Array ( [prices] => Array ( [0] => 5 ) )
        but it still returns
        Array ( [prices] => Array ( [0] => 8 ) )

    /* more things*/


in a class i have the following:

function __construct() {
    add_action('alter_loop', array( $this, 'alter_loop_meta'),10,1);

function alter_loop_meta($meta){
    $meta = apply_filters('some_identifier',$meta);
        at this stage print_r($meta) DOES actually return
        Array ( [prices] => Array ( [0] => 8 ) )

    return $meta;
function my_filter( $meta ) {

    return $meta;

if I use

global $meta; 

in the template file it works (and i can save myself all this filtering as i can just set $meta['prices'][0]='8'; in alter_loop_meta).

however, i am wondering if there's a way to achieve this without any global variables. any hints / links etc much appreciated and - of course - happy to provide more code if necessary ...

1 Answer 1


It won't work the way you are doing it, but you are close. The reason you have to use a global is that you aren't setting your $meta variable with the information returned from the filter.



Should be this:

$meta = apply_filters('alter_loop',$meta);

Note: "Actions" do not return values. "Actions" do things. "Filters" accept data and return it.



  • ah, now you are spelling it out it makes even sense to me . thank you. i've been banging my head against the wall...
    – olly
    Sep 11, 2013 at 15:25
  • one more thing though (just want to make sure this is right as it does seem to do that): if I do NOT call ` add_action('alter_loop', array( $this, 'alter_loop_meta'),10,1); ` anywhere (i.e in the costruct) , it just returns the original $meta value (without any notices / errors such ass "alter_loop" doesnt exist or some such thing ??
    – olly
    Sep 11, 2013 at 15:33
  • Yes, it should give back the original data unless there are functions hooked in... but use filters not actions when you want to return content.
    – s_ha_dum
    Sep 11, 2013 at 15:35
  • because i hit return before finishing the question. now edited..
    – olly
    Sep 11, 2013 at 15:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.