📖 12 min read | 💻 PHP/WordPress | 🚀 Advanced
Whether you're building WordPress plugins, themes, or custom applications, understanding the most used PHP and WordPress functions is crucial. These functions form the backbone of modern web development and can significantly improve your code quality, performance, and maintainability.
In this guide, we'll explore the functions you'll use every day, with practical examples and explanations following WordPress and WordPress VIP coding standards.
Core PHP Functions Every Developer Should Know
isset() / empty() / is_null()
Check variable existence and emptiness with precision.
// isset() - Check if variable exists and is not NULL
$username = 'john_doe';
if ( isset( $username ) ) {
echo 'Username is set';
}
// empty() - Returns TRUE if variable is empty
$email = '';
if ( empty( $email ) ) {
echo 'Email field is required';
}
// is_null() - Check specifically for NULL
$value = null;
if ( is_null( $value ) ) {
echo 'Value is explicitly NULL';
}
When to use: isset() checks existence, empty() checks if value is falsy, is_null() checks explicitly for NULL.
array_map() / array_filter()
Transform and filter arrays functionally.
// array_map() - Apply callback to each array element
$numbers = array( 1, 2, 3, 4, 5 );
$squared = array_map(
function( $num ) {
return $num * $num;
},
$numbers
);
// Result: [1, 4, 9, 16, 25]
// array_filter() - Filter array by callback condition
$posts = get_posts( array( 'numberposts' => -1 ) );
$published_posts = array_filter(
$posts,
function( $post ) {
return 'publish' === $post->post_status;
}
);
Use case: Process collections of data without loops. Keep code clean and functional.
implode() / explode()
Convert between strings and arrays.
// explode() - Split string into array
$tags_string = 'php,wordpress,coding';
$tags_array = explode( ',', $tags_string );
// Result: ['php', 'wordpress', 'coding']
// implode() - Join array into string
$tags = array( 'php', 'wordpress', 'coding' );
$tags_string = implode( ', ', $tags );
// Result: 'php, wordpress, coding'
// Sanitize and escape array elements
$sanitized_tags = array_map( 'sanitize_text_field', $tags_array );
$safe_output = implode( ', ', $sanitized_tags );
echo wp_kses_post( $safe_output );
Important: Always sanitize input data before processing and escape output.
in_array() / array_key_exists()
Search for values and keys in arrays.
// in_array() - Check if value exists
$allowed_roles = array( 'admin', 'editor', 'author' );
$user_role = 'editor';
if ( in_array( $user_role, $allowed_roles, true ) ) {
// Third parameter 'true' enables strict comparison
echo 'User has valid role';
}
// array_key_exists() - Check if key exists
$user_data = array(
'name' => 'John',
'email' => 'john@example.com',
);
if ( array_key_exists( 'name', $user_data ) ) {
echo $user_data['name'];
}
Pro tip: Use strict comparison (third parameter = true) in in_array() to avoid type juggling issues.
sprintf() / printf()
Format strings safely and consistently.
// sprintf() - Return formatted string
$post_title = 'WordPress Development';
$post_count = 42;
$message = sprintf(
'We have %d articles about %s',
$post_count,
$post_title
);
// Result: 'We have 42 articles about WordPress Development'
// Use with internationalization
$translated = sprintf(
__( 'We have %d articles about %s', 'textdomain' ),
$post_count,
$post_title
);
// printf() - Output directly
printf( 'Welcome %s!', 'Developer' );
// Outputs: Welcome Developer!
Advantage: Better for internationalization and prevents concatenation issues.
Essential WordPress Functions
get_option() / update_option()
Manage WordPress site options safely.
// get_option() - Retrieve option value
$site_name = get_option( 'blogname' );
$custom_setting = get_option( 'my_plugin_setting', 'default_value' );
// update_option() - Update option value
update_option( 'my_plugin_setting', 'new_value' );
// Best practice: Sanitize and validate
class Plugin_Settings {
private $option_name = 'my_plugin_settings';
public function get_settings() {
$settings = get_option( $this->option_name, array() );
return $this->validate_settings( $settings );
}
public function save_settings( $new_settings ) {
$sanitized = $this->sanitize_settings( $new_settings );
update_option( $this->option_name, $sanitized );
}
private function sanitize_settings( $settings ) {
return array(
'api_key' => sanitize_text_field( $settings['api_key'] ?? '' ),
'timeout' => absint( $settings['timeout'] ?? 30 ),
);
}
}
Important: Always sanitize and validate option values before saving.
get_posts() / get_post()
Retrieve post data from database.
// get_posts() - Retrieve multiple posts
$args = array(
'post_type' => 'post',
'posts_per_page' => 10,
'orderby' => 'date',
'order' => 'DESC',
's' => sanitize_text_field( $_GET['search'] ?? '' ),
);
$posts = get_posts( $args );
foreach ( $posts as $post ) {
setup_postdata( $post );
echo wp_kses_post( $post->post_title );
}
wp_reset_postdata();
// get_post() - Retrieve single post by ID
$post = get_post( 123 );
if ( $post ) {
echo wp_kses_post( $post->post_content );
}
Remember: Always use wp_reset_postdata() after custom loop and escape all output.
get_post_meta() / update_post_meta()
Handle custom post metadata.
// get_post_meta() - Retrieve post meta
$post_id = get_the_ID();
$author_name = get_post_meta( $post_id, 'author_name', true );
// With default value
$featured_image = get_post_meta(
$post_id,
'featured_image',
true
) ?? 'default-image.jpg';
// Get all meta for a post
$all_meta = get_post_meta( $post_id );
// update_post_meta() - Update or create meta
$author = sanitize_text_field( $_POST['author'] ?? '' );
$post_id = absint( $_POST['post_id'] ?? 0 );
if ( $post_id ) {
update_post_meta(
$post_id,
'author_name',
$author
);
}
Best practice: Always sanitize and validate metadata before saving.
wp_kses_post() / sanitize_text_field()
Secure input and output handling.
// Escape output - wp_kses_post() allows safe HTML
$user_content = get_post_meta( get_the_ID(), 'content', true );
echo wp_kses_post( $user_content );
// Sanitize input - Remove dangerous HTML
$title = sanitize_text_field( $_POST['title'] ?? '' );
$description = wp_kses_post( $_POST['description'] ?? '' );
// Class-based approach following OOP
class Secure_Handler {
/**
* Sanitize user input
*
* @param string $input Raw user input.
* @return string Sanitized input.
*/
public static function sanitize_input( $input ) {
return sanitize_text_field( stripslashes( $input ) );
}
/**
* Escape output safely
*
* @param string $output Content to escape.
* @return string Escaped output.
*/
public static function escape_output( $output ) {
return wp_kses_post( $output );
}
}
⚠️ Critical: Never skip sanitization and escaping. These functions prevent XSS attacks.
do_action() / apply_filters()
Implement the WordPress hook system.
// do_action() - Execute action hooks
do_action( 'my_plugin_init' );
// With parameters
do_action( 'my_plugin_process_data', $user_id, $data );
// apply_filters() - Filter data through hooks
$title = apply_filters( 'my_plugin_title', 'Default Title' );
class Plugin_Core {
/**
* Initialize plugin hooks
*/
public function __construct() {
add_action( 'init', array( $this, 'register_post_types' ) );
add_filter( 'the_content', array( $this, 'modify_content' ) );
}
public function register_post_types() {
do_action( 'my_plugin_before_register' );
// Register custom post type
}
public function modify_content( $content ) {
return apply_filters(
'my_plugin_modify_content',
$content
);
}
}
Philosophy: Hooks make plugins extensible and follow WordPress best practices.
wp_enqueue_script() / wp_enqueue_style()
Load assets properly in WordPress.
// Register and enqueue script
add_action( 'wp_enqueue_scripts', function() {
// Enqueue with dependencies and version
wp_enqueue_script(
'my-plugin-script',
plugins_url( 'assets/script.js', __FILE__ ),
array( 'jquery' ), // Dependencies
'1.0.0', // Version
true // Load in footer
);
// Localize script (pass PHP data to JS)
wp_localize_script(
'my-plugin-script',
'myPluginData',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'my_plugin_nonce' ),
)
);
} );
// Enqueue stylesheet
add_action( 'wp_enqueue_scripts', function() {
wp_enqueue_style(
'my-plugin-style',
plugins_url( 'assets/style.css', __FILE__ ),
array(),
'1.0.0'
);
} );
Tip: Always use proper dependencies, versioning, and localization for maintainability.
Best Practices & Advanced Patterns
1. Error Handling and Validation
Always validate and handle errors gracefully:
class Data_Processor {
/**
* Process user data with validation
*
* @param array $data User data to process.
* @return array|WP_Error Processed data or error.
*/
public function process( $data ) {
// Validate input
if ( ! is_array( $data ) || empty( $data ) ) {
return new WP_Error(
'invalid_data',
__( 'Invalid data provided', 'textdomain' )
);
}
// Sanitize
$sanitized = $this->sanitize_data( $data );
// Process with error handling
try {
$result = $this->execute_process( $sanitized );
return $result;
} catch ( Exception $e ) {
return new WP_Error(
'process_error',
$e->getMessage()
);
}
}
private function sanitize_data( $data ) {
return array_map(
'sanitize_text_field',
$data
);
}
}
2. Caching for Performance
Use WordPress caching to improve performance:
class Data_Retriever {
private $cache_key = 'my_plugin_data_cache';
private $cache_duration = 24 * HOUR_IN_SECONDS;
/**
* Get data with caching
*
* @param int $id Data ID.
* @return mixed Cached or fresh data.
*/
public function get_cached_data( $id ) {
$cache = wp_cache_get(
$this->cache_key . '_' . $id
);
if ( false !== $cache ) {
return $cache;
}
// Data not cached, fetch it
$data = $this->fetch_data( $id );
// Cache the data
wp_cache_set(
$this->cache_key . '_' . $id,
$data,
'',
$this->cache_duration
);
return $data;
}
/**
* Invalidate cache
*/
public function invalidate_cache( $id ) {
wp_cache_delete( $this->cache_key . '_' . $id );
}
}
3. Following PHPCS Standards
✅ Correct:
// Proper spacing and naming
$post_id = absint( $_GET['post_id'] ?? 0 );
$title = sanitize_text_field( $_POST['title'] ?? '' );
// Use tabs for indentation in WordPress
if ( isset( $post_id ) ) {
update_post_meta( $post_id, 'key', $title );
}
❌ Incorrect:
// Poor spacing and variable naming
$pid=$_GET['pid'];
$t=$_POST['t'];
if($pid){
update_post_meta($pid,'k',$t);
}
Quick Reference Table
| Function | Purpose | Return Type |
|---|---|---|
isset() |
Check if variable exists | bool |
empty() |
Check if variable is empty | bool |
get_option() |
Retrieve option value | mixed |
wp_kses_post() |
Safely escape HTML | string |
apply_filters() |
Apply filter hooks | mixed |
wp_cache_get() |
Retrieve cached data | mixed|bool |
sanitize_text_field() |
Remove dangerous characters | string |
wp_enqueue_script() |
Load JavaScript safely | void |
Key Takeaways
✅ Always sanitize input - Use sanitize_text_field(), absint(), floatval()
✅ Always escape output - Use wp_kses_post(), esc_html(), esc_url()
✅ Follow WordPress coding standards - Use tabs, proper spacing, and meaningful names
✅ Leverage hooks - do_action() and apply_filters() make code extensible
✅ Use OOP patterns - Organize code into classes for better maintainability
✅ Implement caching - Use wp_cache_* functions for performance optimization
✅ Handle errors gracefully - Return WP_Error objects and validate inputs
Conclusion
Mastering these PHP and WordPress functions is essential for writing secure, maintainable, and performant code. By following WordPress coding standards, implementing proper sanitization and escaping, and leveraging hooks and OOP patterns, you'll create professional-grade WordPress solutions.
Practice these functions in your projects, and you'll build better WordPress applications that stand the test of time.
Have questions? Share your thoughts in the comments below. Happy coding! 🚀
Top comments (0)