By default, WordPress’s Query Loop block doesn’t allow dynamic linking of buttons to the current post. However, with the new Block Bindings API, you can now bind the url
attribute of a Button block to the current post’s permalink.
Here’s how to do it.
Add the PHP Code to Your Theme or Plugin
Add the following code to your theme’s functions.php
file or to a custom plugin. This registers a new binding source that provides the current post URL to the block editor.
function appiapp_query_loop_button_url_bindings_callback( $source_args, $block_instance, $attribute_name ) {
$post_id = $block_instance->context['postId'];
// Ensure the post is accessible before returning the URL
$post = get_post( $post_id );
if ( ( ! is_post_publicly_viewable( $post ) && ! current_user_can( 'read_post', $post_id ) ) || post_password_required( $post ) ) {
return null;
}
// Check if the requested binding key matches, then return the permalink
if ( isset($source_args['key']) && 'appiapp_query_loop_button_url' === $source_args['key'] ) {
return get_permalink( $post_id );
}
}
function appiapp_query_loop_url_register_block_bindings() {
register_block_bindings_source(
'appiapp/query-loop-button-url',
array(
'label' => __( 'Button Url', 'appiapp' ),
'get_value_callback' => 'appiapp_query_loop_button_url_bindings_callback',
'uses_context' => ['postId']
)
);
}
add_action( 'init', 'appiapp_query_loop_url_register_block_bindings' );
What This Code Does
- Registers a new binding source:
appiapp/query-loop-button-url
- Returns the current post’s URL based on the block context (inside a Query Loop)
- Secures access by checking if the post is viewable or password protected
Add a Button with Dynamic Link Inside a Query Loop
Now you can add a button to your Query Loop block in the block editor and bind its URL dynamically to the current post.
Use this block markup (or construct it visually in the editor with code editing enabled):
<!-- wp:buttons -->
<div class="wp-block-buttons">
<!-- wp:button {"metadata":{"bindings":{"url":{"source":"appiapp/query-loop-button-url","args":{"key":"appiapp_query_loop_button_url"}}}}} -->
<div class="wp-block-button">
<a class="wp-block-button__link wp-element-button">Read more</a>
</div>
<!-- /wp:button -->
</div>
<!-- /wp:buttons -->
The metadata.bindings.url.source
value matches the source you registered in PHP (appiapp/query-loop-button-url
), and the args.key
ensures it retrieves the correct data.
Final Notes
- This method requires WordPress 6.5+, where Block Bindings are supported.
- It’s a great way to improve your block templates without needing custom JavaScript.
- Works perfectly with Query Loops, providing each post item with its correct dynamic link.
If you prefer to make the entire block clickable instead, check out appiapp Clickable Container, our free plugin.