I’m trying to create a basic link control in my WordPress plugin, but I can’t get it to work properly. I ‘ve read the previous answers on here, but still having issues. I also checked out the block-editor component documentation on Github, but the example doesn’t go far enough to address my problem. Here is the code for my Attributes:
const attributes = {
linkText: {
type: 'string',
'selector': '.hero-image__button',
default: ''
},
linkURL: {
type: 'string',
selector: '.hero-image__button',
default: ''
}
};
export default attributes;
Here is the code for my Edit function:
import { TextControl } from '@wordpress/components';
import { __experimentalLinkControl as LinkControl } from '@wordpress/block-editor';
export default function Edit ( { attributes: { linkURL, LinkText }, setAttributes } ) {
const handleLinkChange = ( value ) => {
setAttributes( {
linkURL: value.url
} );
};
return (
<>
<TextControl
value={ linkText }
onChange={ ( linkText ) => setAttributes( { linkText } ) }
/>
<LinkControl
onChange={ handleLinkChange }
value={ linkURL }
/>
</>
);
}
Here is the code for my Save Function:
export default function Save ( { attributes: { linkURL, linkText } } ) {
return (
<a className="hero-image__button" href={ linkURL }>{ linkText }</a>
);
}
Everything saves fine and it looks as expected on the front end. The problem occurs in the admin. After entering the URL the value of the field always comes up “Undefined”. Here is a screenshot of what I get:
When I reload the admin page, the link control field resets completely even though the linkURL value persists:
Any help would be greatly appreciated!