return values from hooks do_action and apply_filters, which is better

Myself wondering among the following methods which is better to update an option value where value to be updated is coming from an ajax callback. Since WordPress Codex clearly says apply_filters is used to return the formatted values where as do_actions for logic function executions.

add_action('wp_ajax_test_action', 'testAction');

///****** Method 1 ********///
function testAction() {
    $test = apply_filters('test_filter', 'test');

    wp_send_json($test);
}

add_filter('test_filter', 'test_filter_function', 10, 1);

function test_filter_function($value) {
   $success = get_option('update_from_test_doaction') !== false ?
                    update_option('update_from_test_doaction', $value, 'yes') : add_option('update_from_test_doaction', $value, '', 'yes');
if($success)
return 'Updated';

return 'Not updated';
}


///****** Method 2 ********///
function testAction() {
    $test = apply_filters('test_filter', 'test');

      $test2 = get_option('update_from_test_doaction', '');

    do_action('test_doaction', $test);

$sendJson = 'Not updated';
if($test != $test2)
$sendJson = 'Updated';

    wp_send_json($sendJson);
}

add_filter('test_filter', 'test_filter_function', 10, 1);

function test_filter_function($value) {
   // $value .= '123';
    return $value;
}

add_action('test_doaction', 'test_doaction_functin', 10, 1);

function test_doaction_functin($value) {
    get_option('update_from_test_doaction') !== false ?
                    update_option('update_from_test_doaction', $value, 'yes') : add_option('update_from_test_doaction', $value, '', 'yes');
}

1 Answer
1

Contrary to the comments… I’d say that you should use filter as in method 1 because…

  1. Message will depend on quite a few things right now, You just do a test if statement, later on message may depend on some other factors ( like maybe validating a nonce on failure giving message ‘None invalid’ ).
  2. Actions help in extending your code’s functionality… later on some other plugin ( or maybe theme, if your plugin get’s incredibly famous 😀 ) may wanna change the message to be more friendly like Sorry, couldn't update.

It’s always easier with filters, remember whenever you have a value involved ( like an output message, or value saved into db ) it’s best to use filters.

Leave a Comment