Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Block bindings: Adds a filter to customize the output of a block bindings source. #6839

Conversation

snehapatil2001
Copy link

@snehapatil2001 snehapatil2001 commented Jun 17, 2024

Ticket: https://core.trac.wordpress.org/ticket/61181

Description

  • This PR introduces a filter to the block_bindings_source_value to allow developers to modify the value returned by any block binding source.

  • This enhancement provides greater flexibility for developers who need to modify the displayed content of a meta value, such as showing "Free!" when the meta value is 0 or unset.

Copy link

github-actions bot commented Jun 17, 2024

The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the props-bot label.

Core Committers: Use this line as a base for the props when committing in SVN:

Props snehapatil02, cbravobernal, gziolo, santosguillamot, bacoords.

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.

Copy link

Test using WordPress Playground

The changes in this pull request can previewed and tested using a WordPress Playground instance.

WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser.

Some things to be aware of

  • The Plugin and Theme Directories cannot be accessed within Playground.
  • All changes will be lost when closing a tab with a Playground instance.
  • All changes will be lost when refreshing the page.
  • A fresh instance is created each time the link below is clicked.
  • Every time this pull request is updated, a new ZIP file containing all changes is created. If changes are not reflected in the Playground instance,
    it's possible that the most recent build failed, or has not completed. Check the list of workflow runs to be sure.

For more details about these limitations and more, check out the Limitations page in the WordPress Playground documentation.

Test this pull request with WordPress Playground.

@SantosGuillamot
Copy link

Thanks for working on this! 🙂 I believe something like this could make sense, but I am not sure how it should be structured. Some of the concerns I have at this point:

  • This filter would only run in the server, which means it would show a different value in the editor. I assume that could be a problem.
  • Does this only apply to post meta or to any binding?
  • If it only applies to post meta, should we add the filter to the bindings logic or directly to get_post_meta / get_metadata function? Does this only apply to bindings or each time you want to retrieve the field?

@gziolo
Copy link
Member

gziolo commented Jun 26, 2024

If it only applies to post meta, should we add the filter to the bindings logic or directly to get_post_meta / get_metadata function? Does this only apply to bindings or each time you want to retrieve the field?

There is already an existing filter in get_metadata_raw used internally:

get_{$meta_type}_metadata

@SantosGuillamot
Copy link

Thinking about this a bit more, I feel more confident that we should probably provide a general filter for bindings that receive the source and the same arguments as get_value_callback. Something similar to the render_block filters. This way, it would be possible to change the value not only of post meta but any other source as well.

@snehapatil2001
Copy link
Author

@SantosGuillamot Introduced a general filter 'block_bindings_source_value' to allow developers to modify the value returned by any block binding source.

Changes Made:

  • Modified the get_value method in the WP_Block_Bindings_Source class to apply the new filter.
  • The filter is applied after the value is retrieved from the source but before it's returned.

Key Benefits:

  1. Flexibility: Works for all binding sources, not just post meta.
  2. Consistency: Functions identically in both the editor and on the front end.
  3. Non-intrusive: It doesn't interfere with existing metadata filters but provides a new layer of customization specific to block bindings.

@bacoords
Copy link

+1 for this concept. I'll give a real world example and you can tell me if you think this feature would help.

I recently wrote a block variation for the image block to pull in the featured image (yes there's a "featured image" block, but the image block has more options, like the lightbox control). I couldn't use the core/postmeta field where the featured image is stored because it returns an attachment ID, not a URL. So I had to create a custom binding source.

It'd be much less overhead if I could have modified the value sent to the block binding API to return the URL of the featured image instead of the attachment ID. But now I have a custom binding source for one simple meta field AND there's no editor preview on my variation.

Feels like this would be a great example of when this feature would be useful.

@SantosGuillamot
Copy link

Thanks for making the changes 🙂 I agree it makes sense to have a filter like this.

I must say that I had this on my to-do list for a while, but I didn't find time yet with the 6.6 release. I'm really sorry for the wait. I would like to take a deeper look and understand better all the use cases.

In the meantime, would it make sense to add some testing? Is this something done for other similar filters?

Feels like this would be a great example of when this feature would be useful.

I'd need to review your implementation, but at first glance, it looks like a good example for this functionality 🙂

Copy link
Member

@gziolo gziolo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Example of how filters are tested in different places:

/**
* @ticket 52138
*/
public function test_filter_block_registration_metadata_settings() {
$filter_metadata_registration = static function ( $settings, $metadata ) {
$settings['api_version'] = $metadata['apiVersion'] + 1;
return $settings;
};
add_filter( 'block_type_metadata_settings', $filter_metadata_registration, 10, 2 );
$result = register_block_type_from_metadata(
DIR_TESTDATA . '/blocks/notice'
);
remove_filter( 'block_type_metadata_settings', $filter_metadata_registration );
$this->assertSame( 3, $result->api_version );
}

This is looking very good and the placement for the filter makes perfect sense. Let's bring it to the finish line.

@SantosGuillamot
Copy link

It seems this is close to being ready. Adding some tests and docs, as suggested below, should be enough to include it in the WordPress 6.7 release.

Thanks a lot for working on it @snehapatil2001! Let us know if you'd like some help in that regard 🙂

Copy link
Member

@gziolo gziolo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left some additional comments clarifying my previous feedback. In addition to that, we still need unit tests to cover the usage as explained in #6839 (review).

Comment on lines 87 to 95
/**
* Filters the output of a block bindings source.
*
* @since 6.7.0
*
* @param mixed $value Value returned by `get_value_callback` after applying the filter.
*/
$value = call_user_func_array( $this->get_value_callback, array( $source_args, $block_instance, $attribute_name ) );
return apply_filters( 'block_bindings_source_value', $value, $this->name, $source_args, $block_instance, $attribute_name );
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It still needs some further refinements, so it gets correctly recognized by the parser that generates the documentation for all filters:

Suggested change
/**
* Filters the output of a block bindings source.
*
* @since 6.7.0
*
* @param mixed $value Value returned by `get_value_callback` after applying the filter.
*/
$value = call_user_func_array( $this->get_value_callback, array( $source_args, $block_instance, $attribute_name ) );
return apply_filters( 'block_bindings_source_value', $value, $this->name, $source_args, $block_instance, $attribute_name );
$value = call_user_func_array( $this->get_value_callback, array( $source_args, $block_instance, $attribute_name ) );
/**
* Filters the value of a block bindings source.
*
* @since 6.7.0
*
* @param mixed $value The computed value for the source.
* @param string $name The name of the source.
* @param array $source_args Array containing source arguments used to look up the override value, i.e. { "key": "foo" }.
* @param WP_Block $block_instance The block instance.
* @param string $attribute_name The name of an attribute.
*/
return apply_filters( 'block_bindings_source_value', $value, $this->name, $source_args, $block_instance, $attribute_name );

@cbravobernal
Copy link
Contributor

I left some additional comments clarifying my previous feedback. In addition to that, we still need unit tests to cover the usage as explained in #6839 (review).

Changes addressed.
Are we sure we want the filter to return a function instead of a value? It's kind of confusing with the name.

function filter_block_bindings_source_value() {
		return function () {
			return 'Filtered value';
		};
	}

Comment on lines 284 to 285

public function test_filter_block_bindings_source_value() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the empty line should get removed.

Suggested change
public function test_filter_block_bindings_source_value() {
public function test_filter_block_bindings_source_value() {

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By the way, I think this test should be general purpose in the first place as it isn't tied to post meta, so maybe render.php in the same folder would be a good fit. Having, two tests could work, too.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll move it to render.php

@gziolo
Copy link
Member

gziolo commented Sep 3, 2024

I left some additional comments clarifying my previous feedback. In addition to that, we still need unit tests to cover the usage as explained in #6839 (review).

Changes addressed. Are we sure we want the filter to return a function instead of a value? It's kind of confusing with the name.

function filter_block_bindings_source_value() {
		return function () {
			return 'Filtered value';
		};
	}

This is what I tested locally and you don't need to pass a function that returns a function:

Index: tests/phpunit/tests/block-bindings/postMetaSource.php
===================================================================
--- tests/phpunit/tests/block-bindings/postMetaSource.php	(revision 58970)
+++ tests/phpunit/tests/block-bindings/postMetaSource.php	(working copy)
@@ -266,4 +266,41 @@
 			'The post content should not include the script tag.'
 		);
 	}
+
+	/**
+	 * Tests that filter `block_bindings_source_value` is applied.
+	 *
+	 * @ticket 61181
+	 */
+	public function test_filter_block_bindings_source_value() {
+		register_meta(
+			'post',
+			'tests_filter_field',
+			array(
+				'show_in_rest' => true,
+				'single'       => true,
+				'type'         => 'string',
+				'default'      => 'Original value',
+			)
+		);
+
+		$filter_value = function ( $value, $source_name, $source_args ) {
+			if ( 'core/post-meta' !== $source_name ) {
+				return $value;
+			}
+			return "Filtered value: {$source_args['key']}";
+		};
+
+		add_filter( 'block_bindings_source_value', $filter_value, 10, 3 );
+
+		$content = $this->get_modified_post_content( '<!-- wp:paragraph {"metadata":{"bindings":{"content":{"source":"core/post-meta","args":{"key":"tests_filter_field"}}}}} --><p>Fallback value</p><!-- /wp:paragraph -->' );
+
+		remove_filter( 'block_bindings_source_value', $filter_value );
+
+		$this->assertSame(
+			'<p>Filtered value: tests_filter_field</p>',
+			$content,
+			'The post content should show the filtered value.'
+		);
+	}
 }

I also updated the test to validate that the args get correctly passed. Like I said in #6839 (comment), there should be another test in render.php that validates that all args are correctly passed to the filter.

@SantosGuillamot
Copy link

I've been testing it locally and everything seems to be working as expected. Once the changes to the render.php tests are made, I believe this should be ready.

@gziolo
Copy link
Member

gziolo commented Sep 3, 2024

I've been testing it locally and everything seems to be working as expected. Once the changes to the render.php tests are made, I believe this should be ready.

Agreed, the existing test for post meta is nice to keep as it covers 3 params ($filter_value = function ( $value, $source_name, $source_args ) {), but there is one more param to cover, and it can work with a custom source fine, too.

@cbravobernal
Copy link
Contributor

I've been testing it locally and everything seems to be working as expected. Once the changes to the render.php tests are made, I believe this should be ready.

Agreed, the existing test for post meta is nice to keep as it covers 3 params ($filter_value = function ( $value, $source_name, $source_args ) {), but there is one more param to cover, and it can work with a custom source fine, too.

Done!

Copy link
Member

@gziolo gziolo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Excellent, this looks solid!

@cbravobernal cbravobernal changed the title Implement a filter to customize output on _block_bindings_post_meta_get_value. Block bindings: Add a filter to customize the output of a block bindings source. Sep 3, 2024
@cbravobernal cbravobernal changed the title Block bindings: Add a filter to customize the output of a block bindings source. Block bindings: Adds a filter to customize the output of a block bindings source. Sep 3, 2024
@cbravobernal
Copy link
Contributor

@colorful-tones
Copy link
Member

@gziolo @cbravobernal

I wonder if this might be a simple and proper example of how to filter a meta value using this new filter?

https://gist.github.com/colorful-tones/b6a2dd85e66dd4adb1d58c0ed1623a61#file-demo-block-bindings-php-L43-L62

@gziolo
Copy link
Member

gziolo commented Oct 2, 2024

@colorful-tones, it’s correct. The reasoning for this new filter is to allow formatting of the value depending on the context. Some examples:

  • store a price as a number but show with different currencies on the page
  • store timestamp but show formatted date
  • add a translated prefix if the value is set

@cbravobernal
Copy link
Contributor

Sure, we can use them for future docs and the dev note.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

6 participants