Category: WordPress

  • Sometimes, an array is passed to the get_callback provided to register_rest_field() instead of an object

    When using register_rest_field() to add fields to terms in the WordPress REST API, the $object sent to your get_callback function will be an array instead of an object like the documentation describes.

    An object will still be passed, sometimes, too. Here is an example of how I work around this problem:

    
    	function add_api_term_fields() {
    
    		//location-phone-hours
    		register_rest_field( 'location', 'location-phone-hours', array(
    			'get_callback'    => array( $this, 'get_term_meta_via_rest' ),
    			'update_callback' => array( $this, 'set_term_meta_via_rest' ),
    			'schema'          => array(
    				'description' => __( 'An array of phone numbers and hours of operation for this location.', 'inventory-portal' ),
    				'type'        => 'string',
    				'context'     => array( 'view', 'edit' ),
    			),
    		) );
    	}
    
    	static function get_term_meta_via_rest( $term, $attr, $request, $object_type ) {
    		$term_id = 0;
    
    		if(  is_array( $term ) ) {
    			$term_id = $term['id']
    		} else {
    			$term_id = $term->term_id;
    		}
    
    		return maybe_serialize( get_term_meta( $term_id, $attr, true ) );
    	}
    

    Why is this happening? See the definition of prepare_item_for_response() method on line 683 of wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php. The call to add_additional_fields_to_object() on line 725 is the method that passes an array to your get_callback.

    Perhaps this is an acceptable design. I believe the only reference to the data type of $object in the documentation is this comment. It certainly feels like a bug.

  • How to add an additional webhook to an Elementor Form

    Elementor Pro includes a form builder widget, complete with a webhook to which all form data can be sent and a redirect URL to send users after successful submissions. I have been tasked with adding a second webhook to a form because the first was being used for an integration with Zapier.

    We need to use the elementor_pro/forms/new_record hook to make this work, and it is possible to prevent the form from submitting if our additional webhook fails. Here is a simple plugin that adds a webhook to all Elementor Forms sitewide:

    https://gist.github.com/csalzano/dfd754e0fe8b6ac10731fad8f257c0bf

    If you need to target a specific form, access the form name or ID using the $record object.

    //Get the Elementor form ID
    $form_id = $record->get_form_settings( 'id' );
    
    //Get the Elementor form name
    $form_name = $record->get_form_settings( 'form_name' );