post-terms-property.php
| 1 | <?php |
| 2 | |
| 3 | |
| 4 | namespace Jet_Form_Builder\Actions\Methods\Post_Modification; |
| 5 | |
| 6 | use Jet_Form_Builder\Actions\Methods\Abstract_Modifier; |
| 7 | use Jet_Form_Builder\Actions\Methods\Base_Object_Property; |
| 8 | use Jet_Form_Builder\Actions\Methods\Object_Dynamic_Property; |
| 9 | |
| 10 | // If this file is called directly, abort. |
| 11 | if ( ! defined( 'WPINC' ) ) { |
| 12 | die; |
| 13 | } |
| 14 | |
| 15 | class Post_Terms_Property extends Base_Object_Property implements Object_Dynamic_Property { |
| 16 | |
| 17 | protected $taxonomies = array(); |
| 18 | |
| 19 | public function get_id(): string { |
| 20 | return 'post_terms'; |
| 21 | } |
| 22 | |
| 23 | public function get_label(): string { |
| 24 | return __( 'Post Terms', 'jet-form-builder' ); |
| 25 | } |
| 26 | |
| 27 | public function is_supported( string $key, $value ): bool { |
| 28 | return false !== strpos( $key, 'jet_tax__' ); |
| 29 | } |
| 30 | |
| 31 | public function do_before( string $key, $value, Abstract_Modifier $modifier ) { |
| 32 | $tax = str_replace( 'jet_tax__', '', $key ); |
| 33 | |
| 34 | if ( ! isset( $this->taxonomies[ $tax ] ) ) { |
| 35 | $this->taxonomies[ $tax ] = array(); |
| 36 | } |
| 37 | |
| 38 | if ( ! is_array( $value ) ) { |
| 39 | $this->taxonomies[ $tax ][] = $this->sanitize_term( $value, $tax ); |
| 40 | |
| 41 | return; |
| 42 | } |
| 43 | |
| 44 | $this->taxonomies[ $tax ] = array_merge( |
| 45 | $this->taxonomies[ $tax ], |
| 46 | array_map( |
| 47 | function ( $term ) use ( $tax ) { |
| 48 | return $this->sanitize_term( $term, $tax ); |
| 49 | }, |
| 50 | $value |
| 51 | ) |
| 52 | ); |
| 53 | } |
| 54 | |
| 55 | /** |
| 56 | * @param Abstract_Modifier|Post_Modifier $modifier |
| 57 | */ |
| 58 | public function do_after( Abstract_Modifier $modifier ) { |
| 59 | /** @var Base_Post_Action $action */ |
| 60 | $action = $modifier->get_action(); |
| 61 | |
| 62 | if ( is_a( $action, Trash_Action::class ) ) { |
| 63 | return; |
| 64 | } |
| 65 | |
| 66 | $id = $action->get_inserted(); |
| 67 | |
| 68 | if ( ! $id ) { |
| 69 | return; |
| 70 | } |
| 71 | |
| 72 | foreach ( $this->taxonomies as $tax => $terms ) { |
| 73 | wp_set_post_terms( $id, $terms, $tax ); |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | protected function sanitize_term( $term, $tax ) { |
| 78 | if ( |
| 79 | is_taxonomy_hierarchical( $tax ) || |
| 80 | ( |
| 81 | is_numeric( $term ) && absint( $term ) === (int) $term |
| 82 | ) |
| 83 | ) { |
| 84 | return absint( $term ); |
| 85 | } |
| 86 | |
| 87 | return esc_html( $term ); |
| 88 | } |
| 89 | } |
| 90 |