WordPress functions give fatal error in included php file

First, my problem is similar to this thread. However, the solution posted there doesn’t work for me.

I’m creating a plugin that displays a contact form on a page using the Shortcode API.

Read More

Plugin folder contents:

  • contact.php (main plugin file)
  • validate.php (included php file)

The main file has the usual plugin header, and WordPress functions called in it work as expected [i.e: get_permalink()]

The validate.php file is included in contact.php as follows:

define ("PLUGIN_PATH", plugin_dir_path(__FILE__));
include_once dirname( __FILE__ ) . '/validate.php';

My problem is any WordPress functions called in validate.php will throw a fatal error. PHP functions work as expected, only WordPress functions are throwing a fatal error:

Fatal error: Call to undefined function sanitize_text_field() in /{FULL WEBSITE PATH}/ralrom-contactform/validate.php 

How should I be including the validate.php file to be able to call WordPress functions from it?

I have tried “require” and “include” variations and all throw the same fatal error.

Before using multiple files, I had a working version as a single file shown here:

Orignal working code under a single php file:
http://pastebin.com/qM5aj9qY

Broken code under two php files:
http://pastebin.com/KUCbg6rJ

Related posts

2 comments

  1. You’re POSTing the form to the validate.php file directly, so the WordPress code isn’t loaded. Instead you need to POST the form to the current URL or the home_url or something like that, and then have the plugin intercept the data and act accordingly, so that the WordPress code is loaded before you use its functions.

  2. Thanks to the comments I figured out that what I was trying to do wasn’t exactly possible.

    The reason being POSTing data to a php page will send the POST data outside of the WordPress loop or “framework”. Therefore the WordPress functions aren’t loaded. A way around this is to require the wordpress files that contain the functions you want to use inside your php page, i.e:

    require_once {path to wordpress wp-includes}/formatting.php;
    

    However, I felt this was a dirty way to do things.

    Instead, I followed Otto’s suggestion and intercepted the POST data before WordPress loaded the page by attaching a function to the “init” hook:

    add_action("init", "intercept_post");
    

    The form action is set to the current page and in the intercept_post function I run data validation, send the email and redirect to the same page. This effectively sends the POST data and prevents a page refresh from submitting the data again.

Comments are closed.