0

I'm trying to execute a PHP script when example.com/12345 is entered as the URL. Is there a specific file where I should place this script, or somewhere in wp-admin where I can set this up?

symlink
  • 11,984
  • 7
  • 29
  • 50
  • What about adding a rewrite rule in `.htaccess` ? Then you can call what ever file you want on what ever URL you want ... – caramba May 09 '17 at 19:11
  • Are you saying you want a command line (CLI) script to run, triggered by a Wordpress page? Or do you just want to put a pretty name on a PHP file? What does this PHP file contain? – LeonardChallis May 09 '17 at 19:12
  • @LeonardChallis pretty name on a PHP file. One idea I have is that it will check $_SERVER for the URL, and execute a small PHP script if the URL matches the criteria. – symlink May 09 '17 at 19:16
  • When you say "PHP file" do you mean a web page? – LeonardChallis May 09 '17 at 19:17
  • http://stackoverflow.com/questions/2810124/how-to-add-a-php-page-to-wordpress See this post – Ashkar May 09 '17 at 19:54
  • @LeonardChallis No, I mean I have a snippet of PHP code, and I need to drop it somewhere so Wordpress will pick it up before a 404 page is served. – symlink May 09 '17 at 20:08
  • Is this specifically for 404 pages? – LeonardChallis May 09 '17 at 20:09
  • @Ashkar it looks like that explains how to add a custom template to a particular page. I need to run a PHP script before a 404 page is served, due to a URL being entered that Wordpress doesn't recognize. – symlink May 09 '17 at 20:09
  • @LeonardChallis not really, but it's for URLs that don't match up with pages that have been added in the admin. So, for all intents and purposes.. – symlink May 09 '17 at 20:10
  • http://stackoverflow.com/questions/17249278/access-standalone-php-file-with-wordpress-installed So you are looking for this . – Ashkar May 09 '17 at 20:20
  • @Ashkar I figured it out, see my answer. Thanks for your help. – symlink May 09 '17 at 20:21

2 Answers2

1

I figured it out. It's as simple as adding a function into functions.php that fires on init:

function custom_rewrite_basic() {
    if(preg_match('~[0-9]~', $_SERVER['PHP_SELF'] )){
        //script goes here
    }
}
add_action('init', 'custom_rewrite_basic');
symlink
  • 11,984
  • 7
  • 29
  • 50
0

You can create an action hook in your functions file to do something when a page is not found:

function page_not_found()
{
    if (is_404()) {
        /* put your custom code here */
    }
}
add_action('template_redirect', 'page_not_found');

Of course, if you want to adjust the condition of when your custom code runs, you can use other functions such as these.

LeonardChallis
  • 7,759
  • 6
  • 45
  • 76