GithubHelp home page GithubHelp logo

brandonkramer / wordpress-plugin-boilerplate Goto Github PK

View Code? Open in Web Editor NEW
104.0 6.0 29.0 211 KB

An organized and object-oriented boilerplate for WordPress plugin development and testing. Includes Composer, Codeception (unit/acceptance testing), PHPCodeSniffer with WordPress Coding Standards to validate your code, TravisCI configuration for automatic testing & continuous integration, Webpack 5 for front-end development incl. BabelJS v7, BrowserSync v2, PostCSS v8, PurgeCSS v3, Autoprefixer, Eslint, Stylelint, SCSS processor, WPPot, and more.

JavaScript 0.17% PHP 99.83%
wordpress plugin wordpress-plugin wordpress-development wordpress-development-kit boilerplate wordpress-boilerplate

wordpress-plugin-boilerplate's Introduction

WordPress Plugin Boilerplate

Build Status PHP 7.1+

Plugin boilerplate with modern tools to kickstart your WordPress project
This includes common and modern tools to facilitate plugin development and testing with an organized, object-oriented structure and kick-start a build-workflow for your WordPress plugins.
  • The Boilerplate is based on the Plugin API , Coding Standards, and Documentation Standards.
  • Includes Composer, Requirements micropackage to test environment requirements for your plugin, Codeception to do unit/acceptance testing, PHPCodeSniffer with WordPress Coding Standards to validate your code, TravisCI configuration for automatic testing & continuous integration, object-oriented code structure for better overview, an automatic class loader that automatically instantiate classes based on type of request.
  • This can be combined with the Webpack 5 workflow for front-end development using the npx quickstart script that includes the Webpack v5 bundler, BabelJS v7, BrowserSync v2, PostCSS v8, PurgeCSS v3, Autoprefixer, Eslint, Stylelint, SCSS processor, WPPot, and more.

Quickstart

Image

Should be run inside your plugins folder (wp-content/plugins).

npx wp-strap plugin

You can also use the npx script with predefined answers to get a quicker start

npx wp-strap plugin "projectName:Your plugin name" "description:Test the plugin" "pluginVersion:1.0.0" license:MIT "author:The Dev Company" authorEmail:[email protected] url:the-dev-company.com webpack:Y codesniffer:Y codeception:Y travisCi:Y css:Sass+PostCSS

It will take a couple of minutes to install after your terminal input; it will clone the git repo's, search and replace all the plugin data, do a composer install, and when it's combined with the Webpack workflow then it wil also do a npm install

Read more about the configuration & build scripts

Features & benefits

Backend

Composer (Namespaces + PSR4 autoloader + Dependency manager)

  • Namespace support to group all of your code under a custom name. That way, your classes, functions, and so on don’t clash with other people’s code running on the site at the same time
  • PSR-4 Autoloader to autoload files and directories in connection with namespaces
  • Includes a dependency manager to easily load in 3rd party libraries from packagist, locked onto specific versions

Object-oriented & classes autoloader

PHPCodeSniffer + WordPress Coding Standards + Automattic's phpcs-neutron-ruleset

  • PHP CodeSniffer is built in with predefined configuration for proper linting. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent.
  • PHPCS is extended with the WordPress Coding Standards & PHPCompatibilityWP for PHP_CodeSniffer which is a collection of PHP_CodeSniffer rules (sniffs) to validate code developed for WordPress. It ensures code quality and adherence to coding conventions, especially the official WordPress Coding Standards.
  • PHPCS is also extented with Automattic's phpcs-neutron-ruleset which is a set of modern (PHP >7) linting guidelines for WordPress development.

Codeception (unit/acceptance testing)

  • Codeception is built in which combines all testing levels (acceptance, functional, integration, unit) with WordPress defined functions, constants, classes and methods in any test.
  • With a flexible set of included modules, tests are easy to write, easy to use, and easy to maintain.

Plugin requirements

  • Requirements micropackage is built in that allows you to test environment requirements to run your plugin. It can test: PHP version, PHP Extensions, WordPress version, Active plugins, Current theme, DocHooks support
  • Easily to configure using a simple array
  • If the plugin doesn't pass the test then it will disable the plugin automatically for the user in WordPress and show a notification in the back-end

TravisCI

  • Ready to use TravisCI configuration for automatic testing & continuous integration which currently only validates the plugin code with PHPCodeSniffer during automated testing when being deployed, but can also be extended to test unit/acceptance cases from Codeception

Prettified errors & Classes debug array

Frontend (Webpack)

For front-end tooling the webpack workflow is being cloned. Read more about this workflow here: https://github.com/wp-strap/wordpress-webpack-workflow

Styling (CSS)

  • Minification in production mode handled by Webpack
  • PostCSS for handy tools during post CSS transformation using Webpack's PostCSS-loader
  • Auto-prefixing using PostCSS's autoprefixer to parse CSS and add vendor prefixes to CSS rules using values from Can I Use. It is recommended by Google and used in Twitter and Alibaba.
  • PurgeCSS which scans your php (template) files to remove unused selectors from your css when in production mode, resulting in smaller css files.
  • Sourcemaps generation for debugging purposes with various styles of source mapping handled by WebPack
  • Stylelint that helps you avoid errors and enforce conventions in your styles. It includes a linting tool for Sass.

Styling when using PostCSS-only

  • Includes postcss-import to consume local files, node modules or web_modules with the @import statement
  • Includes postcss-import-ext-glob that extends postcss-import path resolver to allow glob usage as a path
  • Includes postcss-nested to unwrap nested rules like how Sass does it.
  • Includes postcss-nested-ancestors that introduces ^& selector which let you reference any parent ancestor selector with an easy and customizable interface
  • Includes postcss-advanced-variables that lets you use Sass-like variables, conditionals, and iterators in CSS.

Styling when using Sass+PostCSS

JavaScript

  • BabelJS Webpack loader to use next generation Javascript with a BabelJS Configuration file
  • Minification in production mode
  • Code Splitting, being able to structure JavaScript code into modules & bundles
  • Sourcemaps generation for debugging purposes with various styles of source mapping handled by WebPack
  • ESLint find and fix problems in your JavaScript code with a linting configuration including configurations and custom rules for WordPress development.
  • Prettier for automatic JavaScript / TypeScript code formatting

Images

Translation

  • WP-Pot scans all the files and generates .pot file automatically for i18n and l10n

BrowserSync, Watcher & WebpackBar

  • Watch Mode, watches for changes in files to recompile
  • File types: .css, .html, .php, .js
  • BrowserSync, synchronising browsers, URLs, interactions and code changes across devices and automatically refreshes all the browsers on all devices on changes
  • WebPackBar so you can get a real progress bar while development which also includes a profiler

Configuration

  • All configuration files .prettierrc.js, .eslintrc.js, .stylelintrc.js, babel.config.js, postcss.config.js are organised in a single folder
  • The Webpack configuration is divided into 2 environmental config files for the development and production build/environment

Requirements

File structure

You can add your own new class files by naming them correctly and putting the files in the most appropriate location, see other files for examples. Composer's Autoloader and the Bootstrap class will auto include your file and instantiate the class. The idea of this organisation is to be more conscious of structuring your code.

## First level files
├──the-plugin-name.php           # Main entry file for the plugin
├──composer.json                 # Composer dependencies & scripts
├──phpcs.xml.dist                # PHPCodeSniffer configuration
├──codeception.dist.yml          # Codeception testing configuration
├──.env.testing                  # Codeception testing environment configuration
├──.travis.yml                   # TravisCI configuration for automatic testing & continuous integration
├──package.json                  # (incl. when using webpack) Node.js dependencies & scripts (NPM functions)
├──webpack.config.js             # (incl. when using webpack) Holds all the base Webpack configurations
│
│ ## Folders
├──src                           # Holds all the plugin php classes
│   ├── Bootstrap.php            # Bootstraps the plugin and auto-instantiate classes
│   ├── App                      # Holds the plugin application-specific functionality
│   │   ├── Frontend             # All public-facing hooks/functionality
│   │   ├── Backend              # All admin-specific hooks/functionality
│   │   ├── General              # Hooks/functionality shared between the back-end and frontend
│   │   ├── Cli                  # Code for cli commands
│   │   ├── Cron                 # Code for cron events
│   │   ├── Rest                 # Code for rest api functionalities
│   ├── Config                   # Plugin configuration code
│   │   ├── Classes.php          # Defines the folders and order of classes to init
│   │   ├── I18n.php             # Internationalization and localization definitions
│   │   ├── Plugin.php           # Plugin data which are used through the plugin
│   │   ├── Requirements.php     # Defines the requirements that are needed to run this plugin.
│   │   ├── Setup.php            # Plugin setup hooks (activation, deactivation, uninstall)
│   ├── Common                   # Utilities & helpers shared in the whole plugin 
│   │   ├── Abstracts            # Here you can add abstract classes to extend your php classes
│   │   │   ├── Base.php         # A base class which all classes extends to load in default methods, currently the plugin data is only being injected
│   │   ├── Traits               # Here you can add handy traits to extend your php classes
│   │   │   ├── Requester.php    # The requester trait to determine what we request; used to determine which classes we instantiate in the Bootstrap class
│   │   │   ├── Singleton.php    # The singleton skeleton trait to instantiate the class only once
│   │   ├── Utils                # Here you can add helper/utiliy functions, eg: array functions
│   │   │   ├── Errors.php       # Utility class for the prettified errors and to write debug logs as string or array
│   │   ├── Functions.php        # Main function class for external/global functions, eg: "plugin_name()->your_function"
│   ├── Integrations             # Includes the integration with libraries, api's or other plugins
│   ├── Compatibility            # 3rd party compatibility code
├──tests                         # Codeception test files
├──templates                     # Folder to include all the template files
│   ├── test-template.php        # Example template file
├──languages                     # WordPress default language map in Plugins & Themes
│   ├── the-plugin-name.pot      # Boilerplate POT File that gets overwritten by WP-Pot 
├──webpack                       # (incl. when using webpack) Holds all the sub-config files for webpack
│   ├── .prettierrc.js           # Configuration for Prettier
│   ├── .eslintrc.js             # Configuration for Eslint
│   ├── .stylelintrc.js          # Configuration for Stylelint
│   ├── babel.config.js          # Configuration for BabelJS
│   ├── postcss.config.js        # Configuration for PostCSS
│   ├── config.base.js           # Base config for Webpack's development & production mode
│   ├── config.development.js    # Configuration for Webpack in development mode
│   └── config.production.js     # Configuration for Webpack in production mode
└──assets
    ├── src                      # (incl. when using webpack) Holds all the source files
    │   ├── images               # Uncompressed images
    │   ├── scss/pcss            # Holds the Sass/PostCSS files
    │   │ ├─ frontend.scss/pcss  # For front-end styling
    │   │ └─ backend.scss/pcss   # For back-end / wp-admin styling
    │   └── js                   # Holds the JS files
    │     ├─ frontend.js         # For front-end scripting
    │     └─ backend.js          # For back-end / wp-admin scripting
    │
    └── public
        ├── images               # Optimized (compressed) images
        ├── css                  # Compiled CSS files with be generated here
        └── js                   # Compiled JS files with be generated here

What to configure

  1. When using codeception; configure the environments settings in .env.testing, other configurations can be found in codeception.dist.yml
  2. When using Webpack; edit the BrowserSync settings in webpack.config.js which applies to your local/server environment
    • You can also disable BrowserSync, Eslint & Stylelint in webpack.config.js
    • You may want to configure the files in /webpack/ and webpack.config.js to better suite your needs
  3. You can activate the plugin in WordPress and work on it straight away.

Acceptance & Unit Testing

  • Testing with Codeception works out of the box
  • Create test files with composer generate:wpunit or composer generate:acceptance
  • Write your test methods and run composer run:wpunit or composer run:acceptance
  • Extensive documentation can be found here https://codeception.com/for/wordpress

PHPCodeSniffer

Plugin requirements

  • Set your plugin requirements in src/Config/Requirements.php using a simple array
  • It can test: PHP version, PHP Extensions, WordPress version, Active plugins, Current theme, DocHooks support
  • If the plugin doesn't pass the test then it will be disabled automatically in WordPress and show a notification in the back-end
  • Documentation can be found here: https://github.com/micropackage/requirements

TravisCI

Frontend/Webpack tooling

When using webpack then you can use the following for the front-end build process. Read here more for more information about this workflow.

Developing Locally

To work on the project locally (with Eslint, Stylelint & Prettier active), run:

yarn dev

Or run with watcher & browserSync

yarn dev:watch

This will open a browser, watch all files (php, scss, js, etc) and reload the browser when you press save.

Building for Production

To create an optimized production build (purged with PurgeCSS & fully minified CSS & JS files), run:

yarn prod

Or run with watcher & browserSync

yarn prod:watch

More Scripts/Tasks

# To scan for text-domain functions and generate WP POT translation file
yarn translate

# To find problems in your JavaScript code
yarn eslint 

# To find fix problems in your JavaScript code
yarn eslint:fix

# To find problems in your sass/css code
yarn stylelint

# To find fix problems in your sass/css code
yarn stylelint:fix

# To make sure files in assets/src/js are formatted
yarn prettier

# To fix and format the js files in assets/src/js
yarn prettier:fix

Composer.json dependencies

Depedency Description Version
Plugin Requirements
micropackage/requirements Allows you to test environment requirements to run your plugin. 1.0
PHPCodeSniffer
dealerdirect/phpcodesniffer-composer-installer Allows for easy installation of PHP_CodeSniffer coding standards (rulesets) 0.7.1
wp-coding-standards/wpcs Collection of PHP_CodeSniffer rules (sniffs) to validate code developed for WordPress *
automattic/phpcs-neutron-ruleset Set of modern (PHP >7) linting guidelines for WordPress development 3.3
phpcompatibility/phpcompatibility-wp Analyse the codebase of a WordPress-based project for PHP cross-version compatibility 2.1
Codeception
lucatume/function-mocker A Patchwork powered function mocker to mock function for testing 1.0
lucatume/wp-browser Provides easy acceptance, functional, integration and unit testing for WordPress plugins, themes and whole sites using Codeception 3.0
Codeception/lib-innerbrowser Parent library for all Codeception framework modules and PhpBrowser. 1.0
codeception/module-asserts A Codeception module containing various assertions 1.0
codeception/module-phpbrowser Use to perform web acceptance tests with non-javascript browser 1.0
codeception/module-webdriver Run tests in real browsers using the W3C WebDriver protocol. 1.0
codeception/module-db A database module for Codeception. 1.0
codeception/module-filesystem A Codeception module for testing local filesystem. 1.0
codeception/module-cli A Codeception module for testing basic shell commands and shell output. 1.0
codeception/module-rest A REST module for Codeception 1.2
codeception/util-universalframework Mock framework module used in internal Codeception tests 1.0
codeception/codeception-progress-reporter Reporter for codeception with a progress bar 4.0.2

Package.json dependencies

https://github.com/wp-strap/wordpress-webpack-workflow#packagejson-dependencies

Boilerplate's Changelog

Documenting this project's progress...

January 15, 2021

  • refactor: (webpack/frontend) Migrated from NPM to Yarn for speed, install went from 183.281s to 65.76s-90.02s.

January 14, 2021

  • feat: Added POT File with all the translation strings
  • refactor: Moved classes array to own config file
  • feat: Added npx CLI build script + docs

January 9, 2021

  • refactor: Rename plugin (meta) data to replace-able names

January 8, 2021

  • feat: Added PHP_CodeSniffer with WordPress-Coding-Standards including configuration file
  • feat(.travis.yml): added TravisCI configuration file
  • feat: Added bootstrap classes debugger method
  • feat: README.md file

wordpress-plugin-boilerplate's People

Contributors

brandonkramer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

wordpress-plugin-boilerplate's Issues

Can't run installation command

I'm trying to run the following command:
npx wp-strap plugin "projectName:Archiviciel" "description:Extension en charge de toute la logique métier spécifique au CMS Archiviciel" "pluginVersion:1.0.0" license:MIT "author:Mosaika" authorEmail:[email protected] url:mosaika.fr webpack:Y codesniffer:N codeception:N travisCi:N css:Sass+PostCSS

But it results in a weird git clone error:
Screen 2021-09-08 à 13 00 14

If I try the git clone command by itself, the repo cloning process works fine.

Any idea what is going on?

Thank you!

Best practices

I've used the boilerplate to create a custom plugin to track user engagement analytics on live streamed video assets. included in the plugin within the /public directory are some fairly robust JavaScripts that mesh with a webhook from the stream provider and a AJAX call to track real time player events.
It's my understanding that these scripts added to the enqueue_scripts() function in the public/class-plugin-name-public.php run on every single page in the rather vast WP site I'm intending to deploy it on. This seems inefficient and rather insecure...
What's best practice as far as only getting the scripts to run on specific pages...for instance, making a custom theme template and only applying that template file to a page containing video assets?

File "Bootstrap.php" is capitalized, but install process expects lower case (linux)

When running the install via npx wp-strap plugin, Step 4 fails with the following error message:

✖ 4. Operator is replacing plugin data
Error - Error: No files match the pattern: /home/martin/temp/wp-strap/mos-affililate/src/bootstrap.php
Error - '4. Operator is replacing plugin data' was a required step, exiting now.

But looking at the files that are already there, you can see that there is a Bootstrap.php file, it's just capitalized.

I'm running on linux (Ubuntu based)

Yarn prod output is empty

yarn dev outputs files correctly but when running yarn prod the public folder (output) is empty .

image

Any workarounds or possible fixes ?

package.json

{ "name": "wordpress-webpack-workflow", "version": "1.1.4", "author": "WP-Strap", "license": "MIT", "homepage": "https://github.com/wp-strap/wordpress-webpack-workflow", "description": "Modern WebPack workflow for WordPress front-end development and testing (plugins & themes) with handy tools included.\n", "main": "index.js", "repository": { "type": "git", "url": "https://github.com/wp-strap/wordpress-webpack-workflow.git" }, "bugs": { "url": "https://github.com/wp-strap/wordpress-webpack-workflow/issues" }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "prod": "webpack --env NODE_ENV=production --env production", "prod:watch": "webpack --env NODE_ENV=production --env production --watch", "dev": "webpack --env NODE_ENV=development", "dev:watch": "webpack --env NODE_ENV=development --watch", "eslint": "eslint assets/src/js/**/*.js", "eslint:fix": "eslint assets/src/js/**/*.js --fix", "stylelint": "stylelint assets/src/**/**/*.{css,scss,pcss}", "stylelint:fix": "stylelint assets/src/**/**/*.{css,scss,pcss} --fix", "prettier": "prettier assets/src/js/**/*.js", "prettier:fix": "prettier --write assets/src/js/**/*.js", "translate": "wp-pot --src '**/**/**/*.php' --dest-file 'languages/local-site.pot' --package 'local-site' --domain 'local-site' --last-translator 'WP SCRIPT LAB <[email protected]>' --team 'WP SCRIPT LAB <[email protected]>' --bug-report 'local-site.com'" }, "babel": { "extends": "./webpack/babel.config.js" }, "eslintConfig": { "extends": [ "./webpack/.eslintrc.js" ] }, "prettier": "./webpack/.prettierrc.js", "stylelint": { "ignoreFiles": [ "./assets/public/css/**/*.css", "./vendor/**/**/*.css", "./node_modules/**/**/*.css", "./tests/**/**/*.css" ], "extends": [ "./webpack/.stylelintrc.js" ] }, "dependencies": {}, "devDependencies": { "@babel/core": "^7.12.10", "@babel/eslint-parser": "^7.12.1", "@babel/preset-env": "^7.12.11", "@wordpress/eslint-plugin": "^7.4.0", "autoprefixer": "^10.2.1", "babel-loader": "^8.2.2", "browser-sync": "^2.26.13", "browser-sync-webpack-plugin": "^2.3.0", "copy-webpack-plugin": "^7.0.0", "css-loader": "^5.0.1", "eslint": "^7.17.0", "eslint-webpack-plugin": "^2.4.1", "eslint-plugin-prettier": "^3.3.1", "glob-all": "^3.2.1", "image-minimizer-webpack-plugin": "^2.2.0", "imagemin-gifsicle": "^7.0.0", "imagemin-jpegtran": "^7.0.0", "imagemin-optipng": "^8.0.0", "imagemin-svgo": "^8.0.0", "mini-css-extract-plugin": "^1.3.3", "node-sass-magic-importer": "^5.3.2", "postcss": "^8.2.4", "postcss-advanced-variables": "^3.0.1", "postcss-import": "^14.0.0", "postcss-import-ext-glob": "^2.0.0", "postcss-loader": "^4.1.0", "postcss-nested": "^5.0.3", "postcss-nested-ancestors": "^2.0.0", "prettier": "^2.2.1", "purgecss-webpack-plugin": "^3.1.3", "sass": "^1.32.2", "sass-loader": "^10.1.0", "stylelint": "^13.8.0", "stylelint-scss": "^3.18.0", "stylelint-webpack-plugin": "^2.1.1", "webpack": "^5.12.3", "webpack-cli": "^4.3.1", "webpackbar": "^5.0.0-3", "wp-pot-cli": "^1.5.0" }, "keywords": [ "wordpress", "workflow", "webpack", "theme", "plugin", "WebPack", "BrowserSync", "PostCSS", "Autoprefixer", "PurgeCSS", "BabelJS", "Eslint", "Stylelint", "SCSS", "WP-Pot" ] }

config.production.js

const glob           = require( 'glob-all' );
const PurgecssPlugin = require( 'purgecss-webpack-plugin' )  // A tool to remove unused CSS

module.exports = ( projectOptions ) => {

    process.env.NODE_ENV = 'production';  // Set environment level to 'production'

    /**
     * The base skeleton
     */
    const Base = require( './config.base' )( projectOptions );

    /**
     * CSS rules
     */
    const cssRules = {
        ...Base.cssRules, ...{
            // add CSS rules for production here
        }
    };

    /**
     * JS rules
     */
    const jsRules = {
        ...Base.jsRules, ...{
            // add JS rules for production here
        }
    };

    /**
     * Image rules
     */
    const imageRules = {
        ...Base.imageRules, ...{
            // add image rules for production here
        }
    }

    /**
     * Optimizations rules
     */
    const optimizations = {
        ...Base.optimizations, ...{
            minimize: true,
            splitChunks: {
                cacheGroups: {
                    styles: {  // Configured for PurgeCSS
                        name:    'styles',
                        test:    /\.css$/,
                        chunks:  'all',
                        enforce: true
                    }
                }
            }
            // add optimizations rules for production here
        }
    }

    /**
     * Plugins
     */
    const plugins = [
        ...Base.plugins, ...[
            new PurgecssPlugin( { // Scans files and removes unused CSS
                paths: glob.sync( projectOptions.projectCss.purgeCss.paths, { nodir: true } ),
            } ),
            // add plugins for production here
        ]
    ]

    /**
     * Add sourcemap for production if enabled
     */
    const sourceMap = { devtool: false };
    if ( projectOptions.projectSourceMaps.enable === true && (
        projectOptions.projectSourceMaps.env === 'prod' || projectOptions.projectSourceMaps.env === 'dev-prod'
    ) ) {
        sourceMap.devtool = projectOptions.projectSourceMaps.devtool;
    }

    /**
     * The configuration that's being returned to Webpack
     */
    return {
        mode:         'production',
        entry:        projectOptions.projectJs.entry, // Define the starting point of the application.
        output:       {
            path:     projectOptions.projectOutput,
            filename: projectOptions.projectJs.filename
        },
        devtool:      sourceMap.devtool,
        optimization: optimizations,
        module:       { rules: [ cssRules, jsRules, imageRules ], },
        plugins:      plugins,
    }
}

config.base.js

/**
 * CSS Rules
 */
const cssRules = {
    test:    projectOptions.projectCss.use === 'sass' ? projectOptions.projectCss.rules.sass.test : projectOptions.projectCss.rules.postcss.test,
    exclude: /(node_modules|bower_components|vendor)/,
    use:     [
        MiniCssExtractPlugin.loader, // Creates `style` nodes from JS strings
        "css-loader",  // Translates CSS into CommonJS
        {  // loads the PostCSS loader
            loader:  "postcss-loader",
            options: require( projectOptions.projectCss.postCss )( projectOptions )
        }
    ],
};

if ( projectOptions.projectCss.use === 'sass' ) { // if chosen Sass then we're going to add the Sass loader
    cssRules.use.push( { // Compiles Sass to CSS
        loader:  'sass-loader',
        options: {
            sassOptions: { importer: magicImporter() }  // add magic import functionalities to sass
        }
    } );
}

/**
 * JavaScript rules
 */
const jsRules = {
    test:    projectOptions.projectJs.rules.test,
    include: projectOptions.projectJsPath,
    exclude: /(node_modules|bower_components|vendor)/,
    use:     'babel-loader' // Configurations in "webpack/babel.config.js"
};

/**
 * Images rules
 */
const imageRules = {
    test: projectOptions.projectImages.rules.test,
    use:  [
        {
            loader: 'file-loader',// Or `url-loader` or your other loader
        },
    ],
}

/**
 * Optimization rules
 */
const optimizations = {};

/**
 * Plugins
 */
const plugins = [
    new WebpackBar( // Adds loading bar during builds
        // Uncomment this to enable profiler https://github.com/nuxt-contrib/webpackbar#options
        // { reporters: [ 'profile' ], profile: true }
    ),
    new MiniCssExtractPlugin( { // Extracts CSS files
        filename: projectOptions.projectCss.filename
    } ),
    new CopyPlugin( { // Copies images from src to public
        patterns: [ { from: projectOptions.projectImagesPath, to: projectOptions.projectOutput + '/images' }, ],
    } ),
    new ImageMinimizerPlugin( { // Optimizes images
        minimizerOptions: projectOptions.projectImages.minimizerOptions,
    } ),
];
// Add browserSync to plugins if enabled
if ( projectOptions.browserSync.enable === true ) {
    const browserSyncOptions = {
        files: projectOptions.browserSync.files,
        host:  projectOptions.browserSync.host,
        port:  projectOptions.browserSync.port,
    }
    if ( projectOptions.browserSync.mode === 'server' ) {
        Object.assign( browserSyncOptions, { server: projectOptions.browserSync.server } )
    } else {
        Object.assign( browserSyncOptions, { proxy: projectOptions.browserSync.proxy } )
    }
    plugins.push( new BrowserSyncPlugin( browserSyncOptions, { reload: projectOptions.browserSync.reload } ) )
}

return {
    cssRules: cssRules, jsRules: jsRules, imageRules: imageRules, optimizations: optimizations, plugins: plugins
}
}

webpack.config.js

/**

This is a main entrypoint for Webpack config.
@SInCE 1.0.0
*/
const path = require( 'path' );
// Paths to find our files and provide BrowserSync functionality.
const projectPaths = {
projectDir: __dirname, // Current project directory absolute path.
projectJsPath: path.resolve( __dirname, 'assets/src/js' ),
projectScssPath: path.resolve( __dirname, 'assets/src/scss' ),
projectImagesPath: path.resolve( __dirname, 'assets/src/images' ),
projectOutput: path.resolve( __dirname, 'assets/public' ),
projectWebpack: path.resolve( __dirname, 'webpack' ),
};

// Files to bundle
const projectFiles = {
// BrowserSync settings
browserSync: {
enable: true, // enable or disable browserSync
host: 'localhost',
port: 3000,
mode: 'proxy', // proxy | server
server: { baseDir: [ 'public' ] }, // can be ignored if using proxy
proxy: 'local-site.local',
// BrowserSync will automatically watch for changes to any files connected to our entry,
// including both JS and Sass files. We can use this property to tell BrowserSync to watch
// for other types of files, in this case PHP files, in our project.
files: '//.php',
reload: true, // Set false to prevent BrowserSync from reloading and let Webpack Dev Server take care of this
// browse to http://localhost:3000/ during development,
},
// JS configurations for development and production
projectJs: {
eslint: true, // enable or disable eslint | this is only enabled in development env.
filename: 'js/[name].js',
entry: {
frontend: projectPaths.projectJsPath + '/frontend.js',
backend: projectPaths.projectJsPath + '/backend.js',
},
rules: {
test: /.m?js$/,
}
},
// CSS configurations for development and production
projectCss: {
postCss: projectPaths.projectWebpack + '/postcss.config.js',
stylelint: true, // enable or disable stylelint | this is only enabled in development env.
filename: 'css/[name].css',
use: 'sass', // sass || postcss
// ^ If you want to change from Sass to PostCSS or PostCSS to Sass then you need to change the
// styling files which are being imported in "assets/src/js/frontend.js" and "assets/src/js/backend.js".
// So change "import '../sass/backend.scss'" to "import '../postcss/backend.pcss'" for example
rules: {
sass: {
test: /.s[ac]ss$/i
},
postcss: {
test: /.pcss$/i
}
},
purgeCss: { // PurgeCSS is only being activated in production environment
paths: [ // Specify content that should be analyzed by PurgeCSS
__dirname + '/assets/src/js//',
__dirname + '/templates///',
__dirname + '/template-parts///',
__dirname + '/blocks///',
__dirname + '/*.php',
]
}
},
// Source Maps configurations
projectSourceMaps: {
// Sourcemaps are nice for debugging but takes lots of time to compile,
// so we disable this by default and can be enabled when necessary
enable: false,
env: 'dev', // dev | dev-prod | prod
// ^ Enabled only for development on default, use "prod" to enable only for production
// or "dev-prod" to enable it for both production and development
devtool: 'source-map' // type of sourcemap, see more info here: https://webpack.js.org/configuration/devtool/
// ^ If "source-map" is too slow, then use "cheap-source-map" which struck a good balance between build performance and debuggability.
},
// Images configurations for development and production
projectImages: {
rules: {
test: /.(jpe?g|png|gif|svg)$/i,
},
// Optimization settings
minimizerOptions: {
// Lossless optimization with custom option
// Feel free to experiment with options for better result for you
// More info here: https://webpack.js.org/plugins/image-minimizer-webpack-plugin/
plugins: [
[ 'gifsicle', { interlaced: true } ],
[ 'jpegtran', { progressive: true } ],
[ 'optipng', { optimizationLevel: 5 } ],
[ 'svgo', {
plugins: [
{ removeViewBox: false, },
],
}, ],
],
}
}
}

// Merging the projectFiles & projectPaths objects
const projectOptions = {
...projectPaths, ...projectFiles,
projectConfig: {
// add extra options here
}
}

// Get the development or production setup based
// on the script from package.json
module.exports = env => {
if ( env.NODE_ENV === 'production' ) {
return require( './webpack/config.production' )( projectOptions );
} else {
return require( './webpack/config.development' )( projectOptions );
}
};

Any help would be greatly appreciated .

Configured plugin values not substituted in template - "{{The Plugin Name}}"

Just tried running npx wp-strap plugin to initialize a plugin, went through the setup steps and filled in all the details, no errors were shown.

After completing, the placeholder values haven't been replaced with the data I entered, so my plugin main file looks like this:

<?php
/**
 * {{The Plugin Name}}
 *
 * @package   {{the-plugin-name}}
 * @author    {{author_name}} <{{author_email}}>
 * @copyright {{author_copyright}}
 * @license   {{author_license}}
 * @link      {{author_url}}
 *
 * Plugin Name:     {{The Plugin Name}}
 * Plugin URI:      {{plugin_url}}
 * Description:     {{plugin_description}}
 * Version:         {{version}}
 * Author:          {{author_name}}
 * Author URI:      {{author_url}}
 * Text Domain:     the-plugin-name-text-domain
 * Domain Path:     /languages
 * Requires PHP:    7.1
 * Requires WP:     5.5.0
 * Namespace:       ThePluginName
 */

Log:

 __        ______      ____  _
 \ \      / /  _ \    / ___|| |_ _ __ __ _ _ __
  \ \ /\ / /| |_) |___\___ \| __| '__/ _` | '_ \
   \ V  V / |  __/_____|__) | |_| | | (_| | |_) |
    \_/\_/  |_|       |____/ \__|_|  \__,_| .__/
                                          |_|
Create a new WordPress project
? Please enter your project name (e.g. The Plugin Name): My Cool Plugin
? The plugin description:
? The plugin version (default: 1.0.0): 1.0.0
? The plugin license (default: MIT): MIT
? The plugin author's name (e.g. The Dev Company):
? The plugin author's e-mail address (e.g. [email protected]):
? The author url without https:// (e.g. the-dev-company.com):
? Use WebPack for front-end (SCSS/JS) tooling (Y/n) no
? Use PHP CodeSniffer with WP Coding Standards to validate the code for WordPress (Y/n) yes
? Use Codeception for functional, integration & acceptance tests (Y/n) yes
? Use Travis CI for automatic testing & continuous integration (Y/n) yes

Summary:
- projectName: My Cool Plugin
- description:
- pluginVersion: 1.0.0
- license: MIT
- author:
- authorEmail:
- url:
- webpack: no
- codesniffer: yes
- codeception: yes
- travisCi: yes
- vendor:
- package: my-cool-plugin
- namespace: MyCoolPlugin
- prefix: MY_COOL_PLUGIN
- lowerCasePrefix: my_cool_plugin
? Looks good? Yes


✔ 1. Operator is cloning plugin repository
✔ 2. Operator is replacing plugin data
✔ 3. Operator is installing Composer dependencies
✔ 4. Operator is cleaning up
----------------
✔ Project is created

The plugin data, namespace, prefixes has been changed according to your input.
If you use Codeception for testing then you need to configure your local testing environment in .env.testing
If you use webpack then edit the BrowserSync settings in webpack.config.js if you want to make use of it.

Please read the documentation https://github.com/wp-strap/wordpress-plugin-boilerplate if you run into any issues or if you have any questions.

You can activate the plugin in WordPress and work on it straight away. Good luck!

Multiple requirement of autoload.php

My wp-strap plugin is being included in a composer.json of its parent project. It includes other packages such as wordpress, theme, and other plugins. Some of these other packages also need to include an autoload.php for their dependencies. Composer makes one autoload.php that consolidates all the dependencies of the entire parent project. The autoload.php needs to be required in wp-config.php. However, the wp-strap the-plugin-name.php also must require autoload.php in order to create the Bootstrap class. It comes out autoload.php will be required more than once. Is there a way to avoid the multiple requirement of autoload.php?

Fatal error: Uncaught TypeError: vsprintf()

On running composer phpcs i get the following errors :

./vendor/bin/phpcs
EEEEEEEEPHP Fatal error:  Uncaught TypeError: vsprintf(): Argument #2 ($values) must be of type array, string given in C:\Users\feelit\Local Sites\local-site\app\public\wp-content\plugins\local-site\vendor\squizlabs\php_codesniffer\src\Files\File.php:1056
Stack trace:
#0 C:\Users\feelit\Local Sites\local-site\app\public\wp-content\plugins\local-site\vendor\squizlabs\php_codesniffer\src\Files\File.php(1056): vsprintf()
#1 C:\Users\feelit\Local Sites\local-site\app\public\wp-content\plugins\local-site\vendor\squizlabs\php_codesniffer\src\Files\File.php(672): PHP_CodeSniffer\Files\File->addMessage()
#2 C:\Users\feelit\Local Sites\local-site\app\public\wp-content\plugins\local-site\vendor\squizlabs\php_codesniffer\src\Files\File.php(780): PHP_CodeSniffer\Files\File->addError()
#3 C:\Users\feelit\Local Sites\local-site\app\public\wp-content\plugins\local-site\vendor\wp-coding-standards\wpcs\WordPress\Sniffs\WhiteSpace\ControlStructureSpacingSniff.php(395): PHP_CodeSniffer\Files\File->addFixableError()
#4 C:\Users\feelit\Local Sites\local-site\app\public\wp-content\plugins\local-site\vendor\wp-coding-standards\wpcs\WordPress\Sniff.php(910): WordPressCS\WordPress\Sniffs\WhiteSpace\ControlStructureSpacingSniff->process_token()
#5 C:\Users\feelit\Local Sites\local-site\app\public\wp-content\plugins\local-site\vendor\squizlabs\php_codesniffer\src\Files\File.php(498): WordPressCS\WordPress\Sniff->process()
#6 C:\Users\feelit\Local Sites\local-site\app\public\wp-content\plugins\local-site\vendor\squizlabs\php_codesniffer\src\Files\LocalFile.php(130): PHP_CodeSniffer\Files\File->process()
#7 C:\Users\feelit\Local Sites\local-site\app\public\wp-content\plugins\local-site\vendor\squizlabs\php_codesniffer\src\Runner.php(628): PHP_CodeSniffer\Files\LocalFile->process()
#8 C:\Users\feelit\Local Sites\local-site\app\public\wp-content\plugins\local-site\vendor\squizlabs\php_codesniffer\src\Runner.php(434): PHP_CodeSniffer\Runner->processFile()
#9 C:\Users\feelit\Local Sites\local-site\app\public\wp-content\plugins\local-site\vendor\squizlabs\php_codesniffer\src\Runner.php(114): PHP_CodeSniffer\Runner->run()
#10 C:\Users\feelit\Local Sites\local-site\app\public\wp-content\plugins\local-site\vendor\squizlabs\php_codesniffer\bin\phpcs(18): PHP_CodeSniffer\Runner->runPHPCS()
#11 C:\Users\feelit\Local Sites\local-site\app\public\wp-content\plugins\local-site\vendor\bin\phpcs(120): include('...')
#12 {main}
  thrown in C:\Users\feelit\Local Sites\local-site\app\public\wp-content\plugins\local-site\vendor\squizlabs\php_codesniffer\src\Files\File.php on line 1056
Script ./vendor/bin/phpcs handling the phpcs event returned with error code 255

Environment : local ;
PHP : 7.4+

WP Cli Failing Executing commands after activating plugin.

WP Cli fails with the error below as first argument of class_exists needs to be a string in src/App/Cli/Example.php#L38.

Error: Test Plugin 1.0.0 › Fatal ErrorPlugin initialize failed. Could not load class "TestPlugin\App\Cli\Example".

The "init" method is probably missing or try a `composer dumpautoload -o` to refresh the autoloader.

https://github.com/wp-strap/wordpress-plugin-boilerplate/blob/3f02a0e85eea155ad7fbece85a6abe52ec3a9629/src/App/Cli/Example.php#L31-L41

yarn translate : The system cannot find the file specified.

Describe the bug
package.json has this script:

"translate": "wp-pot --src '**/**/**/*.php' --dest-file 'languages/test-plugin.pot' --package 'test-plugin' --domain 'test-plugin' --last-translator 'Test Plugin <[email protected]>' --team 'Test Plugin <[email protected]>' --bug-report 'testplugin.com'"

When i run yarn translate i get the following error:

yarn run v1.22.19
$ wp-pot --src '**/**/**/*.php' --dest-file 'languages/test-plugin.pot' --package 'test-plugin' --domain 'test-plugin' --last-translator 'Test Plugin <[email protected]>' --team 'Test Plugin <[email protected]>' --bug-report 'testplugin.com'
The system cannot find the file specified.
error Command failed with exit code 1.

To Reproduce
run yarn translate (wp-pot)

This will throw the following error:
The system cannot find the file specified.
error Command failed with exit code 1.

Module versions
└─┬ [email protected]
└─┬ [email protected]
└── [email protected]

Additional context
What can cause this issue, can't find anything related to it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.