Archived topic
Button with a fixed domain and prefix with dynamic permalink
5 replies · Started by Ashia on January 13, 2023
Hello, can anyone help me with this, I am using GP pro, Generateblocks pro,
I am wanting to create a button in an Element (Block), a button with fixed domain and prefix(path like "/download/"), and dynamic permalink. e.g: https://domain.com/download/ (dynamic permalink)/ , here domain.com, and /download/ are fixed but after that, the permalink should be dynamic.
For example, if I am on this post "https://domain.com/self-motivation-pdf/" then the button on this post should be like "https://domain.com/download/self-motivation-pdf/", the same goes for all posts.
I am using plugins like generateblocks pro, and advanced custom fields, if any of these can help in this.
Hi there,
i would try.
1 Create a helper function to get the current permalink and string replace the home_url with home_url/download
function make_download_url(){
return esc_url( str_replace( home_url(), home_url() . '/download', get_permalink() ) );
}
2 Use that function in render_block filter to swap a # href with your new download URL:
add_filter( 'render_block', function( $block_content, $block ) {
if (
!is_admin()
&& ! empty( $block['attrs']['className'] )
&& 'download-link' === $block['attrs']['className']
){
$url = make_download_url();
$block_content = str_replace( '#', $url , $block_content );
}
return $block_content;
}, 10, 2 );
3. Add a Button to your page, in the href field just add a # and in the Advanced > CSS Class(es) add: download-link
The # will get swapped out for your new dynamic url.
Thanks a lot, David, if you tell me one more thing it would be like icing on the cake.
I want another button clicking that will add "/India/" at the end of the current URL. e.g: I am on this page "domain.com/about/" and there is a button on this page, when I click it, will go to "domain.com/about/india". here India is fixed. This will be the same for all the pages where I add this button, clicking it will add /India/ at the end of the current URL.
Try this, it will swap the # for that string in a block with a CSS Class of: india-link
Note: you can change what class to look for in this line: && 'india-link' === $block['attrs']['className']
add_filter( 'render_block', function( $block_content, $block ) {
if (
!is_admin()
&& ! empty( $block['attrs']['className'] )
&& 'india-link' === $block['attrs']['className']
){
$url = esc_url( get_permalink() );
$new_url = $url . 'india/';
$block_content = str_replace( '#', $new_url , $block_content );
}
return $block_content;
}, 10, 2 );
Thanks a lot David, another easiest option I missed, adding "India" at the end of every url, is just adding "India" in button href field. Clicking that button always add "/India" in the end of the current post slug.
Thanks a lot David for helping me.
Doh :) glad to hear you got it working !!