Source Code

/shortcode-plugin-template/

shortcode-plugin-template.php

<?php
/**
 * Plugin Name: Shortcode Plugin Template
 * Plugin URI: 
 * Description: Template for a shortcode plugin. It shows how to integrate PHP, JS, CSS and database access into a shortcode. 
 * Version: 1.0.0
 * Text Domain: shortcode-plugin-template
 * Author: Maximilian Brandmaier
 * Author URI: https://www.brandmaier-webentwicklung.de
 */
 
//The following code will add the JS and CSS files of the plugin permanently to every Wordpress page
function loadJS(){
    //Load the Javascript of the plugin to the Wordpress footer
    //If you don't want to load the Javascript on every page, include it into the shortcode output
    wp_enqueue_script( 'shortcode-plugin-template', plugin_dir_url( __FILE__ ) . '/scripts/main.js', false, false, true );
}
add_action( 'wp_enqueue_scripts', 'loadJS' );
 
function loadCSS(){
    //Load the CSS of the plugin to the Wordpress header
    //If you don't want to load the CSS on every page, include it into the shortcode output
    wp_enqueue_style( 'shortcode-plugin-template', plugin_dir_url( __FILE__ ) . '/styles/main.css');
}
add_action( 'wp_enqueue_scripts', 'loadCSS' );
 
//The following code will be run when the plugin is activated
function activatePlugin() {
 
    //Load variables needed to database access
    global $wpdb;
	$tablename = $wpdb->prefix . 'shortcode_plugin_template';
	$charset_collate = $wpdb->get_charset_collate();
 
    //Create a new table in the database
	$sql = "CREATE TABLE $tablename (
		id mediumint(9) NOT NULL AUTO_INCREMENT,
		counter int NOT NULL,
		PRIMARY KEY  (id)
	) $charset_collate;";
	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $sql );
 
    //Add the initial data into the database
    $wpdb->insert( 
		$tablename, 
		array( 
			'counter' => 0,
		) 
	);
 
}
register_activation_hook( __FILE__, 'activatePlugin' );
 
//The following code will be run when the shortcode is viewed in a Wordpress article or page
function requestShortcode($atts) {
 
    //Run and output the results of the PHP code in the folder components
    ob_start();
    include('components/main.php');
    $content = ob_get_contents();
    ob_end_clean();
    return $content;
}
add_shortcode('shortcode-name', 'requestShortcode');