I am new in word press, i want to hit function inside "functions.php" in my website url,how can i do this ? Here is my function in "functions.php", i want to use this function like "http://myurl.com/folder_contents"
function folder_contents() {
echo "Hello world";
// your code here
die();
}
My Answer:
To call a function from functions.php in the URL in WordPress, you can create a custom endpoint using the add_rewrite_rule() function. Here's how you can achieve this:
1. Add the following code to your theme's functions.php file:
php
function custom_rewrite_rule() {
add_rewrite_rule('^folder_contents/?$', 'index.php?folder_contents=1', 'top');
}
add_action('init', 'custom_rewrite_rule');
function custom_query_vars($query_vars) {
$query_vars[] = 'folder_contents';
return $query_vars;
}
add_filter('query_vars', 'custom_query_vars');
function custom_template_redirect() {
if (get_query_var('folder_contents')) {
folder_contents();
exit;
}
}
add_action('template_redirect', 'custom_template_redirect');
function folder_contents() {
echo "Hello world";
// your code here
die();
}
2. After adding the above code, you will need to flush the rewrite rules. You can do this by going to Settings > Permalinks in your WordPress admin dashboard and clicking on the "Save Changes" button.
3. Now you can access the function by visiting http://myurl.com/folder_contents in your browser. This will trigger the folder_contents() function and display "Hello world" on the page.
Please note that directly calling functions in the URL is not a recommended practice in WordPress as it can pose security risks. Make sure to sanitize and validate any input data before using it in your functions to prevent vulnerabilities.
Rate this post
4 of 5 based on 6610 votesComments