WordPress block theme issue – solved!

A selfie of a woman in glasses making a heart with her hands, with hearts flying overhead

What a difference a day makes! Overnight a very kind person from cyberia/eu answered my Mastodon plea and gave me multiple ways to achieve my goal. They also confirmed that my problem with the custom shortcode approach is a current known bug in WordPress core.

Since I already had the child theme set up, I followed their advice to use the new Block Bindings API. I made one small change in the callback function to check if the user is logged in before displaying the link. It works perfectly! No need for the Tampermonkey hack anymore. 🙂

For the sake of posterity, here’s what I put in functions.php:

<?php
add_action( 'init', function() {
  register_block_bindings_source( 'webgoddess/edit-link', array(
    'label' => __( '[Edit]', 'webgoddess' ),
    'get_value_callback' => 'webgoddess_editlink_binding'
  ));
});

function webgoddess_editlink_binding() {
  if (is_user_logged_in () ) {
    return '<a href="' . get_edit_post_link($post->ID) . '">[Edit]</a>';
  } else {
    return;
}
?>

And here’s what I put in my template where I wanted the link to appear:

<!-- wp:paragraph {"metadata":{"bindings":{"content":{"source":"webgoddess/edit-link"}}}} -->
<p>[Edit]</p>
<!-- /wp:paragraph -->

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.


Important Note

This site features content going all the way back to 2000. The posts you’ll read reflect my views and writing style at the time. While I have gone back to clean up a few of them, I think it’s important not to sanitise too much. This site is a record of who I am and how I’ve grown. Any blog post written years ago may not reflect who I am today, nor how I would write about the same topic today.