WordPress
World's largest market share CMS. Rich theme and plugin ecosystem with beginner-friendly interface.
CMS
WordPress
Overview
WordPress is the world's most popular open-source content management system (CMS). Born as a blogging platform in 2003, it now powers over 43.4% of all websites. Built with PHP and MySQL, its flexibility and extensibility enable it to handle diverse applications from blogs to corporate websites and e-commerce stores.
Details
WordPress is renowned for its ease of use and rich features. With its famous 5-minute installation process, intuitive admin dashboard, powerful plugin system, and thousands of themes, even users with limited technical knowledge can build professional websites.
Key Features:
- Plugin Ecosystem: Over 59,000 free plugins available
- Theme System: Thousands of themes to choose from
- Gutenberg Editor: Intuitive block-based content editing
- Multisite Functionality: Manage multiple sites from one installation
- RESTful API: Can be used as a headless CMS
- Multilingual Support: Translated into 200+ languages
- SEO Optimization: Automatic URL generation, metadata management, etc.
Pros and Cons
Pros
- Easy to use, manageable by non-technical users
- Huge community and support system
- Extensive plugins and themes
- Regular security updates
- Free to use (open source)
- SEO-friendly structure
- Mobile responsive support
- High degree of customization freedom
Cons
- Performance degradation with excessive plugin use
- Security vulnerabilities (targeted due to popularity)
- Compatibility issues during updates
- Performance challenges with large-scale sites
- Database structure limitations
- PHP knowledge required for customization
References
- WordPress Official Site
- WordPress Codex (Developer Documentation)
- WordPress Developer Resources
- WordPress Plugin Directory
- WordPress Theme Directory
- WordPress REST API Handbook
Examples
1. Hello World (Basic Setup)
functions.php (Adding Theme Features)
<?php
// Theme setup
function my_theme_setup() {
// Title tag support
add_theme_support('title-tag');
// Featured image support
add_theme_support('post-thumbnails');
// Register custom menus
register_nav_menus(array(
'primary' => __('Primary Menu', 'my-theme'),
'footer' => __('Footer Menu', 'my-theme')
));
}
add_action('after_setup_theme', 'my_theme_setup');
// Enqueue styles and scripts
function my_theme_scripts() {
wp_enqueue_style('my-theme-style', get_stylesheet_uri());
wp_enqueue_script('my-theme-script',
get_template_directory_uri() . '/js/script.js',
array('jquery'), '1.0.0', true
);
}
add_action('wp_enqueue_scripts', 'my_theme_scripts');
2. Theme Development
index.php (Main Template)
<?php get_header(); ?>
<main id="main" class="site-main">
<?php if (have_posts()) : ?>
<div class="posts-container">
<?php while (have_posts()) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<h2 class="entry-title">
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</h2>
<div class="entry-meta">
<?php echo get_the_date(); ?> |
<?php the_author(); ?> |
<?php the_category(', '); ?>
</div>
</header>
<?php if (has_post_thumbnail()) : ?>
<div class="entry-thumbnail">
<?php the_post_thumbnail('medium'); ?>
</div>
<?php endif; ?>
<div class="entry-content">
<?php the_excerpt(); ?>
</div>
<footer class="entry-footer">
<a href="<?php the_permalink(); ?>" class="read-more">
<?php _e('Read More', 'my-theme'); ?> →
</a>
</footer>
</article>
<?php endwhile; ?>
<div class="pagination">
<?php the_posts_pagination(array(
'mid_size' => 2,
'prev_text' => __('← Previous', 'my-theme'),
'next_text' => __('Next →', 'my-theme'),
)); ?>
</div>
</div>
<?php else : ?>
<p><?php _e('No posts found.', 'my-theme'); ?></p>
<?php endif; ?>
</main>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
3. Plugin Development
my-plugin.php (Basic Plugin Structure)
<?php
/**
* Plugin Name: My Custom Plugin
* Plugin URI: https://example.com/my-plugin
* Description: A plugin that adds custom functionality
* Version: 1.0.0
* Author: Your Name
* Author URI: https://example.com
* License: GPL v2 or later
* Text Domain: my-plugin
*/
// Prevent direct access
if (!defined('ABSPATH')) {
exit;
}
// Plugin activation
register_activation_hook(__FILE__, 'my_plugin_activate');
function my_plugin_activate() {
// Create database table
global $wpdb;
$table_name = $wpdb->prefix . 'my_plugin_data';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
value text NOT NULL,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
// Register shortcode
add_shortcode('my_custom_shortcode', 'my_custom_shortcode_handler');
function my_custom_shortcode_handler($atts) {
$atts = shortcode_atts(array(
'title' => 'Default Title',
'color' => 'blue'
), $atts);
ob_start();
?>
<div class="my-custom-box" style="border-color: <?php echo esc_attr($atts['color']); ?>">
<h3><?php echo esc_html($atts['title']); ?></h3>
<p>This is custom content from my plugin!</p>
</div>
<?php
return ob_get_clean();
}
// Add admin menu
add_action('admin_menu', 'my_plugin_admin_menu');
function my_plugin_admin_menu() {
add_menu_page(
'My Plugin Settings',
'My Plugin',
'manage_options',
'my-plugin',
'my_plugin_admin_page',
'dashicons-admin-generic',
20
);
}
function my_plugin_admin_page() {
?>
<div class="wrap">
<h1>My Plugin Settings</h1>
<form method="post" action="options.php">
<?php settings_fields('my_plugin_settings'); ?>
<?php do_settings_sections('my_plugin_settings'); ?>
<?php submit_button(); ?>
</form>
</div>
<?php
}
4. Custom Post Types
custom-post-type.php (Registering Custom Post Type)
<?php
// Register custom post type "Product"
add_action('init', 'register_product_post_type');
function register_product_post_type() {
$labels = array(
'name' => 'Products',
'singular_name' => 'Product',
'add_new' => 'Add New',
'add_new_item' => 'Add New Product',
'edit_item' => 'Edit Product',
'new_item' => 'New Product',
'view_item' => 'View Product',
'search_items' => 'Search Products',
'not_found' => 'No products found',
'not_found_in_trash' => 'No products found in Trash',
'menu_name' => 'Products'
);
$args = array(
'labels' => $labels,
'public' => true,
'has_archive' => true,
'menu_icon' => 'dashicons-cart',
'supports' => array('title', 'editor', 'thumbnail', 'excerpt', 'custom-fields'),
'rewrite' => array('slug' => 'products'),
'show_in_rest' => true // Gutenberg editor support
);
register_post_type('product', $args);
}
// Register custom taxonomy "Product Categories"
add_action('init', 'register_product_taxonomy');
function register_product_taxonomy() {
$labels = array(
'name' => 'Product Categories',
'singular_name' => 'Product Category',
'search_items' => 'Search Categories',
'all_items' => 'All Categories',
'parent_item' => 'Parent Category',
'parent_item_colon' => 'Parent Category:',
'edit_item' => 'Edit Category',
'update_item' => 'Update Category',
'add_new_item' => 'Add New Category',
'new_item_name' => 'New Category Name',
'menu_name' => 'Product Categories'
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_in_rest' => true,
'rewrite' => array('slug' => 'product-category')
);
register_taxonomy('product_category', 'product', $args);
}
// Add custom fields (without ACF)
add_action('add_meta_boxes', 'add_product_meta_boxes');
function add_product_meta_boxes() {
add_meta_box(
'product_details',
'Product Details',
'product_details_callback',
'product',
'normal',
'high'
);
}
function product_details_callback($post) {
wp_nonce_field('product_details_nonce', 'product_details_nonce');
$price = get_post_meta($post->ID, '_product_price', true);
$sku = get_post_meta($post->ID, '_product_sku', true);
?>
<table class="form-table">
<tr>
<th><label for="product_price">Price</label></th>
<td>
<input type="text" id="product_price" name="product_price"
value="<?php echo esc_attr($price); ?>" class="regular-text" />
</td>
</tr>
<tr>
<th><label for="product_sku">SKU</label></th>
<td>
<input type="text" id="product_sku" name="product_sku"
value="<?php echo esc_attr($sku); ?>" class="regular-text" />
</td>
</tr>
</table>
<?php
}
// Save custom fields
add_action('save_post_product', 'save_product_details');
function save_product_details($post_id) {
if (!isset($_POST['product_details_nonce']) ||
!wp_verify_nonce($_POST['product_details_nonce'], 'product_details_nonce')) {
return;
}
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
if (!current_user_can('edit_post', $post_id)) {
return;
}
if (isset($_POST['product_price'])) {
update_post_meta($post_id, '_product_price',
sanitize_text_field($_POST['product_price']));
}
if (isset($_POST['product_sku'])) {
update_post_meta($post_id, '_product_sku',
sanitize_text_field($_POST['product_sku']));
}
}
5. Database Operations
database-operations.php (Database Operations using WPDB)
<?php
// Using the global $wpdb object
global $wpdb;
// 1. Insert data
function insert_custom_data($name, $value) {
global $wpdb;
$table_name = $wpdb->prefix . 'my_custom_table';
$result = $wpdb->insert(
$table_name,
array(
'name' => $name,
'value' => $value,
'created_at' => current_time('mysql')
),
array('%s', '%s', '%s') // Data type specification
);
if ($result === false) {
error_log('Database insert failed: ' . $wpdb->last_error);
return false;
}
return $wpdb->insert_id;
}
// 2. Retrieve data
function get_custom_data($limit = 10) {
global $wpdb;
$table_name = $wpdb->prefix . 'my_custom_table';
// Using prepared statements (SQL injection prevention)
$results = $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM $table_name ORDER BY created_at DESC LIMIT %d",
$limit
)
);
return $results;
}
// 3. Get specific data
function get_custom_data_by_name($name) {
global $wpdb;
$table_name = $wpdb->prefix . 'my_custom_table';
$result = $wpdb->get_row(
$wpdb->prepare(
"SELECT * FROM $table_name WHERE name = %s",
$name
)
);
return $result;
}
// 4. Update data
function update_custom_data($id, $name, $value) {
global $wpdb;
$table_name = $wpdb->prefix . 'my_custom_table';
$result = $wpdb->update(
$table_name,
array(
'name' => $name,
'value' => $value,
'updated_at' => current_time('mysql')
),
array('id' => $id),
array('%s', '%s', '%s'),
array('%d')
);
return $result !== false;
}
// 5. Delete data
function delete_custom_data($id) {
global $wpdb;
$table_name = $wpdb->prefix . 'my_custom_table';
$result = $wpdb->delete(
$table_name,
array('id' => $id),
array('%d')
);
return $result !== false;
}
// 6. Execute custom query
function get_statistics() {
global $wpdb;
$table_name = $wpdb->prefix . 'my_custom_table';
// Get statistics
$stats = $wpdb->get_results("
SELECT
COUNT(*) as total_records,
COUNT(DISTINCT name) as unique_names,
MAX(created_at) as last_created
FROM $table_name
");
return $stats[0];
}
// 7. Transaction processing (WordPress 5.5+)
function complex_database_operation($data_array) {
global $wpdb;
// Start transaction
$wpdb->query('START TRANSACTION');
try {
foreach ($data_array as $data) {
$result = insert_custom_data($data['name'], $data['value']);
if (!$result) {
throw new Exception('Insert failed');
}
}
// Commit
$wpdb->query('COMMIT');
return true;
} catch (Exception $e) {
// Rollback
$wpdb->query('ROLLBACK');
error_log('Transaction failed: ' . $e->getMessage());
return false;
}
}
6. API Integration
rest-api.php (REST API Implementation)
<?php
// Register custom REST API endpoints
add_action('rest_api_init', function () {
// Get products list
register_rest_route('myapi/v1', '/products', array(
'methods' => 'GET',
'callback' => 'get_products_api',
'permission_callback' => '__return_true', // Public API
'args' => array(
'per_page' => array(
'default' => 10,
'sanitize_callback' => 'absint',
),
'page' => array(
'default' => 1,
'sanitize_callback' => 'absint',
),
),
));
// Get single product
register_rest_route('myapi/v1', '/products/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'get_single_product_api',
'permission_callback' => '__return_true',
'args' => array(
'id' => array(
'validate_callback' => function($param, $request, $key) {
return is_numeric($param);
}
),
),
));
// Create product (authentication required)
register_rest_route('myapi/v1', '/products', array(
'methods' => 'POST',
'callback' => 'create_product_api',
'permission_callback' => function() {
return current_user_can('edit_posts');
},
'args' => array(
'title' => array(
'required' => true,
'sanitize_callback' => 'sanitize_text_field',
),
'content' => array(
'required' => true,
'sanitize_callback' => 'wp_kses_post',
),
'price' => array(
'required' => false,
'sanitize_callback' => 'sanitize_text_field',
),
),
));
});
// Get products list API callback
function get_products_api($request) {
$per_page = $request->get_param('per_page');
$page = $request->get_param('page');
$args = array(
'post_type' => 'product',
'posts_per_page' => $per_page,
'paged' => $page,
'post_status' => 'publish',
);
$query = new WP_Query($args);
$products = array();
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$products[] = array(
'id' => get_the_ID(),
'title' => get_the_title(),
'content' => get_the_content(),
'excerpt' => get_the_excerpt(),
'price' => get_post_meta(get_the_ID(), '_product_price', true),
'sku' => get_post_meta(get_the_ID(), '_product_sku', true),
'featured_image' => get_the_post_thumbnail_url(get_the_ID(), 'full'),
'date' => get_the_date('c'),
'link' => get_permalink(),
);
}
}
wp_reset_postdata();
return new WP_REST_Response(array(
'products' => $products,
'total' => $query->found_posts,
'pages' => $query->max_num_pages,
'current_page' => $page,
), 200);
}
// Get single product API callback
function get_single_product_api($request) {
$id = $request->get_param('id');
$post = get_post($id);
if (!$post || $post->post_type !== 'product') {
return new WP_Error(
'product_not_found',
'Product not found',
array('status' => 404)
);
}
$product = array(
'id' => $post->ID,
'title' => $post->post_title,
'content' => apply_filters('the_content', $post->post_content),
'excerpt' => $post->post_excerpt,
'price' => get_post_meta($post->ID, '_product_price', true),
'sku' => get_post_meta($post->ID, '_product_sku', true),
'featured_image' => get_the_post_thumbnail_url($post->ID, 'full'),
'gallery' => get_post_meta($post->ID, '_product_gallery', true),
'categories' => wp_get_post_terms($post->ID, 'product_category',
array('fields' => 'names')),
'date' => get_the_date('c', $post),
'modified' => get_the_modified_date('c', $post),
'author' => get_the_author_meta('display_name', $post->post_author),
'link' => get_permalink($post->ID),
);
return new WP_REST_Response($product, 200);
}
// Create product API callback
function create_product_api($request) {
$title = $request->get_param('title');
$content = $request->get_param('content');
$price = $request->get_param('price');
$post_data = array(
'post_title' => $title,
'post_content' => $content,
'post_type' => 'product',
'post_status' => 'draft', // Create as draft
'post_author' => get_current_user_id(),
);
$post_id = wp_insert_post($post_data);
if (is_wp_error($post_id)) {
return new WP_Error(
'product_creation_failed',
'Failed to create product',
array('status' => 500)
);
}
// Save custom fields
if ($price) {
update_post_meta($post_id, '_product_price', $price);
}
return new WP_REST_Response(array(
'id' => $post_id,
'message' => 'Product created successfully',
'link' => get_permalink($post_id),
), 201);
}
// JWT authentication example (requires JWT authentication plugin)
add_filter('rest_authentication_errors', function($result) {
// Skip if user is already logged in
if (!empty($result)) {
return $result;
}
// Check Authorization header
$auth_header = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if (strpos($auth_header, 'Bearer ') === 0) {
$token = substr($auth_header, 7);
// Verify JWT token (implementation omitted)
$user_id = verify_jwt_token($token);
if ($user_id) {
wp_set_current_user($user_id);
return true;
}
}
return $result;
});