John Davidson

php - How can I make a button in wordpress theme redirect to a specific template onclick?

0 comments
Message:


So I have this code in php:


add_filter( 'template_include', 'my_callback' );


function my_callback( $original_template ) {
if ( some_condition() ) {
return SOME_PATH . '/some-custom-file.php';
} else {
return $original_template;
}
}

and I want to re-write this code in order to use it inside an <a> element and specifically in an onclick="" attribute of that <a> element. All in all my main goal is to create 2 template files in my theme's folder where one is for most recent posts and the other is for the most popupal posts, and the use the code above but inside the <a> element to be able to redirect to each one respectively.


Any suggestions? Thanks in advance,

Jameu



My Answer:
You can achieve this by using JavaScript to handle the redirection when the button is clicked. Here's an example of how you can modify your code to achieve this:

1. Modify your PHP code to include a custom query parameter in the URL when redirecting to the custom template files:

php
add_filter( 'template_include', 'my_callback' );

function my_callback( $original_template ) {
if ( isset( $_GET['template'] ) ) {
$template = $_GET['template'];
if ( $template === 'recent' ) {
return SOME_PATH . '/some-custom-file-recent.php';
} elseif ( $template === 'popular' ) {
return SOME_PATH . '/some-custom-file-popular.php';
}
}
return $original_template;
}


2. In your WordPress theme template file, add an anchor tag with an onclick event that redirects to the custom template files based on the query parameter:

html
View Recent Posts
View Popular Posts




With this setup, when the anchor tags are clicked, the `redirectToTemplate` function will set the query parameter in the URL and redirect to the custom template file based on the selected template (recent or popular).

Rate this post

4 of 5 based on 6508 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us