Make WordPress Core

Ticket #38929: test-wp-hook.php

File test-wp-hook.php, 2.2 KB (added by dd32, 7 years ago)
Line 
1<?php
2
3function append_1($a) { return $a . 1; }
4function append_2($a) { return $a . 2; }
5function append_3($a) { return $a . 3; }
6
7// Before WP_Hook loads, we'll define a filter that should automatically convert.
8$wp_filter['test_filter'][10]['test-key'] = array( 'function' => 'append_1', 'accepted_args' => 1 );
9
10include 'src/wp-includes/plugin.php';
11
12// This will output `01`, as it's been migrated to a WP_Hook
13echo 'filter1: ' . apply_filters( 'test_filter', 0 ) . "\n";
14
15// This will apply fine
16add_filter( 'test_filter', 'append_2' );
17// and output '012'
18echo 'filter1: ' . apply_filters( 'test_filter', 0 ) . "\n";
19
20// This will fail, with a `PHP Notice: Indirect modification of overloaded element of WP_Hook has no effect`
21$wp_filter['test_filter'][10]['test-key-3'] = array( 'function' => 'append_3', 'accepted_args' => 1 );
22// This will echo 012 again.
23echo 'filter1: ' . apply_filters( 'test_filter', 0 ) . "\n";
24// However, this will succeed (Thanks to the `WP_Hook::offsetSet()` method
25$wp_filter['test_filter'][10] = array( 'test-key-3' => array( 'function' => 'append_3', 'accepted_args' => 1 ) );
26// But will have overwritten the exisitng filters and echo `03`
27echo 'filter1: ' . apply_filters( 'test_filter', 0 ) . "\n";
28
29// Direct modifications to append something would have to be done like so:
30$ten = $wp_filter['test_filter'][10];
31$ten['test-key-2'] = array( 'function' => 'append_2', 'accepted_args' => 1 );
32$wp_filter['test_filter'][10] = $ten;
33
34// and will now echo `032`.
35echo 'filter1: ' . apply_filters( 'test_filter', 0 ) . "\n";
36
37// -----
38
39// This filter will be added just-fine though, as it's not already set
40$wp_filter['test_filter2'][10]['test-key-2'] = array( 'function' => 'append_1', 'accepted_args' => 1 );
41
42// This would `Fatal error: Uncaught Error: Call to a member function apply_filters() on array`
43// echo 'filter2: ' . apply_filters( 'test_filter2', 0 ) . "\n";
44
45// Because the filters hadn't been 'upgraded' to WP_Hook after the `$wp_filter` modifications.
46$wp_filter = WP_Hook::build_preinitialized_hooks( $wp_filter ); 
47// This now outputs `01`.
48echo 'filter2: ' . apply_filters( 'test_filter2', 0 ) . "\n";
49
50// Filter1 will still output `032` though because it was preserved.
51echo 'filter1: ' . apply_filters( 'test_filter', 0 ) . "\n";
52
53echo "\n";