Giter Site home page Giter Site logo

hlashbrooke / wordpress-plugin-template Goto Github PK

View Code? Open in Web Editor NEW
1.0K 72.0 329.0 172 KB

A robust code template for creating a standards-compliant WordPress plugin.

Home Page: https://hughlashbrooke.com/

License: GNU General Public License v2.0

JavaScript 7.08% Shell 7.81% PHP 85.05% CSS 0.06%

wordpress-plugin-template's Introduction

This repo has been archived. It is now read-only and will no longer be updated or maintained. You are welcome to fork it and create your own plugins using it. More info here.


WordPress Plugin Template

A robust and GPL-licensed code template for creating a standards-compliant WordPress plugin.

Why this template?

After writing many WordPress plugins I slowly developed my own coding style and way of doing things - this template is the culmination of what I've learnt along the way. I use this template as a base for any plugin that I start building and I thought it might benefit more people if I shared it around.

How do I use it?

You can simply copy the files out of this repo and rename everything as you need it, but to make things easier I have included a shell script in this repo that will automatically copy the files to a new folder, remove all traces of the existing git repo, rename everything in the files according to your new plugin name, and initialise a new git repo in the folder if you choose to do so.

Running the script

You can run the script just like you would run any shell script - it does not take any arguments, so you don't need to worry about that. Once you start the script it will ask for three things:

  1. Plugin name - this must be the full name of your plugin, with correct capitalisation and spacing.
  2. Destination folder - this will be the folder where your new plugin will be created - typically this will be your wp-content/plugins folder. You can provide a path that is relative to the script, or an absolute path - either will work.
  3. Include Grunt support (y/n) - if you enter 'y' here then the Grunt files will be included in the new plugin folder.
  4. Initialise new git repo (y/n) - if you enter 'y' here then a git repo will be initialised in the new plugin folder.

API functions

As of v3.0 of this template, there are a few libraries built into it that will make a number of common tasks a lot easier. I will expand on these libraries in future versions.

Registering a new post type

Using the post type API and the wrapper function from the main plugin class you can easily register new post types with one line of code. For example if you wanted to register a listing post type then you could do it like this:

WordPress_Plugin_Template()->register_post_type( 'listing', __( 'Listings', 'wordpress-plugin-template' ), __( 'Listing', 'wordpress-plugin-template' ) );

Note that the WordPress_Plugin_Template() function name and the wordpress-plugin-template text domain will each be unique to your plugin after you have used the cloning script.

This will register a new post type with all the standard settings. If you would like to modify the post type settings you can use the {$post_type}_register_args filter. See the WordPress codex page for all available arguments.

Registering a new taxonomy

Using the taxonomy API and the wrapper function from the main plugin class you can easily register new taxonomies with one line of code. For example if you wanted to register a location taxonomy that applies to the listing post type then you could do it like this:

WordPress_Plugin_Template()->register_taxonomy( 'location', __( 'Locations', 'wordpress-plugin-template' ), __( 'Location', 'wordpress-plugin-template' ), 'listing' );

Note that the WordPress_Plugin_Template() function name and the wordpress-plugin-template text domain will each be unique to your plugin after you have used the cloning script.

This will register a new taxonomy with all the standard settings. If you would like to modify the taxonomy settings you can use the {$taxonomy}_register_args filter. See the WordPress codex page for all available arguments.

Defining your Settings Page Location

Using the filter {base}menu_settings you can define the placement of your settings page. Set the location key to options, menu or submenu. When using submenu also set the parent_slug key to your preferred parent menu, e.g themes.php. For example use the following code to let your options page display under the Appearance parent menu.

$settings['location'] = 'submenu';
$settings['parent_slug'] = 'themes.php';

See respective codex pages for location option defined below: https://codex.wordpress.org/Function_Reference/add_options_page https://developer.wordpress.org/reference/functions/add_menu_page/ https://developer.wordpress.org/reference/functions/add_submenu_page/

Calling your Options

Using the Settings API and the wrapper function from the main plugin class you can easily store options from the WP admin like text boxes, radio options, dropdown, etc. You can call the values by using id that you have set under the settings_fields function. For example you have the id - text_field, you can call its value by using get_option('wpt_text_field'). Take note that by default, this plugin is using a prefix of wpt_ before the id that you will be calling, you can override that value by changing it under the __construct function $this->base variable;

What does this template give me?

This template includes the following features:

  • Plugin headers as required by WordPress & WordPress.org
  • Readme.txt file as required by WordPress.org
  • Main plugin class
  • Full & minified Javascript files
  • Grunt.js support
  • Standard enqueue functions for the dashboard and the frontend
  • A library for easily registering a new post type
  • A library for easily registering a new taxonomy
  • A library for handling common admin functions (including adding meta boxes to any post type, displaying settings fields and display custom fields for posts)
  • A complete and versatile settings class like you see here
  • A .pot file to make localisation easier
  • Full text of the GPLv2 license

See the changelog for a complete list of changes as the template develops.

I've got an idea/fix for the template

If you would like to contribute to this template then please fork it and send a pull request. Please submit all pull requests to the develop branch. I'll merge the request if it fits into the goals for the template and credit you in the changelog.

This template is amazing! How can I ever repay you?

There's no need to credit me in your code for this template, just go forth and use it to make the WordPress experience a little better.

wordpress-plugin-template's People

Contributors

carl-alberto avatar collinprice avatar cralberto11 avatar ffabiosales avatar gustavoedinger avatar hlashbrooke avatar jeffikus avatar jonathanbossenger avatar kidsil avatar kloon avatar leogopal avatar loweryaustin avatar mohamedhamad avatar mrsonord avatar natrio42 avatar rafasashi avatar thebeard avatar theericdevelops avatar tjbp avatar wpdelighter 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  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

wordpress-plugin-template's Issues

Sanitize tabs

In order to pass PHPCS, I've changed the following lines in Class _Settings:

334:	$current_section = $_POST['tab'];
	$current_section = sanitize_text_field( wp_unslash( $_POST['tab'] ) );
337:	$current_section = $_GET['tab'];
	$current_section = sanitize_text_field( wp_unslash( $_GET['tab'] ) );
409:	$tab .= $_GET['tab'];
	$tab .= sanitize_text_field( wp_unslash( $_GET['tab'] ) );

These fields should never contain HTML anyway so this seems a good way to handle this unless there's some edge case I haven't thought of.

I would open a pull request, but I'm still learning how to use version control and haven't figured out how to do that yet :-(

Unselecting all options of checkbox_multi generates error.

Warning: in_array() expects parameter 2 to be array, string given in "...-admin-api.php" on line 112

It looks like when you unselect all the options in a checkbox_multi field, it is saved as an empty string, rather than an empty array. Trying to loop through the option as an array, or in this case use the in_array() test, Wordpress generates an error.

_register_args filter?

This bit:

This will register a new post type with all the standard settings. If you would like to modify the post type settings you can use the {$post_type}_register_args filter. See the WordPress codex page for all available arguments.

it's a bit obscure. If I create the new post type with something along the lines as:

$post = YSLS_CT()->register_post_type(
    'test',
    __('tests', 'ysls-ct'),
    __('test', 'ysls-ct'));

How would I access the _register_tags filter to change some of the arguments for register_post_type?

Settings Image Won't Add

First of all, go in the plugin's settings page.
The following steps are to reproduce the issue:

  1. Add an image using "Upload new image"
  2. The image thumbnail will show.
  3. Remove the image using "Remove image"
  4. Add a new image using "Upload new image"
  5. The image won't add.

Widgets and Shortcodes

Wondering if you have thoughts on adding example code on how to incorporate adding a widget and a shortcode (with media button) to this plugin starter?

If not, could you point me to a quality tutorial? :)

Thanks!

Hook html content in frontend & backend footer

I would like to use your template to develop a plugin with it.

I need to hook some html content every where in the frontend and backend footers of a wordpress installation.

How do you suggest me to do that and where to put the hooks in your template?

PHP-codesniffer says: use a nonce on the tabbed settings.

PHPCS throws this warning when run against includes/class-my-plugin-settings.php: WARNING | Processing form data without nonce verification. I've included all of the errors for thoroughness but most of them are easy fixes. The nonce error I have no idea how to fix, or even if it should be fixed.

The affected lines are 251, 252, 254, 255, 317, 318, & 331.

--------------------------------------------------------------------------------------
FOUND 9 ERRORS AND 15 WARNINGS AFFECTING 17 LINES
--------------------------------------------------------------------------------------
  15 | WARNING | Property name "$_instance" should not be prefixed with an underscore
	 |         | to indicate visibility
  91 | WARNING | In footer ($in_footer) is not set explicitly wp_register_script; It
	 |         | is recommended to load scripts in the footer. Please set this value
	 |         | to `true` to load it in the footer, or explicitly `false` if it
	 |         | should be loaded in the header.
 251 | ERROR   | Processing form data without nonce verification.
 251 | ERROR   | Processing form data without nonce verification.
 252 | ERROR   | Processing form data without nonce verification.
 254 | WARNING | Processing form data without nonce verification.
 254 | WARNING | Processing form data without nonce verification.
 255 | WARNING | Processing form data without nonce verification.
 261 | WARNING | Found: !=. Use strict comparisons (=== or !==).
 303 | ERROR   | All output should be run through an escaping function (see the
	 |         | Security sections in the WordPress Developer Handbooks), found
	 |         | '$html'.
 317 | WARNING | Processing form data without nonce verification.
 317 | WARNING | Processing form data without nonce verification.
 318 | WARNING | Processing form data without nonce verification.
 331 | WARNING | Processing form data without nonce verification.
 332 | WARNING | Found: ==. Use strict comparisons (=== or !==).
 336 | WARNING | Processing form data without nonce verification.
 336 | WARNING | Found: ==. Use strict comparisons (=== or !==).
 336 | WARNING | Processing form data without nonce verification.
 343 | WARNING | Processing form data without nonce verification.
 371 | ERROR   | All output should be run through an escaping function (see the
	 |         | Security sections in the WordPress Developer Handbooks), found
	 |         | '$html'.
 397 | ERROR   | All output should be run through an escaping function (see the
	 |         | Security sections in the WordPress Developer Handbooks), found '__'.
 397 | ERROR   | All output should be run through an escaping function (see the
	 |         | Security sections in the WordPress Developer Handbooks), found
	 |         | '$this'.
 406 | ERROR   | All output should be run through an escaping function (see the
	 |         | Security sections in the WordPress Developer Handbooks), found '__'.
 406 | ERROR   | All output should be run through an escaping function (see the
	 |         | Security sections in the WordPress Developer Handbooks), found
	 |         | '$this'.
--------------------------------------------------------------------------------------

updated_messages missing dollar sign

I found a strange behavior when posting new custom post_types that are defined in the plugin. There is a missing dollar sign in the line for function updated_messages for message 6

6 => sprintf( __( '%1$s published. %2$sView %3$s%4s.' , 'wordpress-plugin-template' ), $this->single, '<a href="' . esc_url( get_permalink( $post_ID ) ) . '">', $this->single, '</a>' ),

the last %4s should read $4$s

Metaboxes

Great job! Could help implement Metaboxes by functions of the plugin! I miss several attempts with what is described in other threads and I could not make it work in any way.
Sorry for the English, is translated from google.
Thank you.

Label type setting

Hi,
I would like to have a setting that I could change it by code (for example: last time cache refresh) and just show the value in settings but to disable textfield or just to write the value to avoid saving that setting.

And I would like to add a extra button between settings to refresh cache. How would be the best way to do this in the plugin template?

Thanks!

dirs.css vs less.css

Isn't this an error?

        less: {
            compile: {
                options: {
                    // These paths are searched for @imports
                    paths: ['<%= less.css %>/']
                },
                files: [{
                    expand: true,
                    cwd: '<%= dirs.css %>/',

Shoudn't it read "paths: ['<%= dirs.css %>']"?

Having more than one image field in the settings page causes another issue.

Hello, sorry for bothering you again.
Have you ever tried to use two image type fields?
I have two settings with type="image", they have different ID's but when I select media for both setting fields and update...one is lost or overridden by the last select media file.

Maybe you can point me into the right direction.
Thank you

The select field option is not woking

I am creating a social network post type which is working well. But when i add the metabox fields for select box isn't working.

My code is as folows:
// social_nav Post-type Pedamuse()->register_post_type( 'social_nav', __( 'Social Navigation', 'pedamuse' ), __( 'Social Navigation', 'pedamuse' ) );

// Add a metabox to social_nav post types add_action( 'add_meta_boxes', 'pedamuse_social_nav'); function pedamuse_social_nav(){ Pedamuse()->admin->add_meta_box ('social_navigation_meta',__( 'Social Navigation Links', 'pedamuse' ), array('social_nav')); }

// Add custom post fieds to social_navigation_meta metabox add_filter( 'social_nav_custom_fields', 'social_custom_fields', 10, 2 );

function social_custom_fields ( $fields, $post_type ) { $metabox = 'social_navigation_meta';

$fields = array( array( // Resource Name 'metabox' => $metabox, 'id' => 'social_name', 'label' => __( 'Resource Name', 'pedamuse' ), 'description' => __( 'Enter Social Netwrok Name', 'pedamuse' ), 'type' => 'text', 'default' => '', 'placeholder' => '' ),

array( 'metabox' => $metabox, 'id' => 'social_link', 'label' => __( 'Social URL/ Link' , 'pedamuse' ), 'description' => __( 'What is the url / web adress that links to your social profile', 'pedamuse' ), 'type' => 'url', 'default' => '', 'placeholder' => __( '//www.fb.com/foo', 'pedamuse' ) ),

array( // not working 'id' => 'social_select_name', 'label' => __( 'Social Netwrok', 'pedamuse' ), 'type' => 'select', 'options' => array( 'facebook' => 'Facebook', 'twitter' => 'Twitter', 'linkedin' => 'LinkedIn', 'instagram' => 'Instagram', 'pinterest' => 'Pinterest' ), 'default' => 'facebook' ),

);

return $fields; }

Did i miss something?

checkbox default 'on' not working

Hello,
checkbox default 'on' not working

when settings screen gets loaded the first time after plugin activation, the checkbox is unchecked.

I am on the latest WP (5.0.3) and PHP 7.2

Any help would be greatly appreciated

				array(  //A standard checkbox - if you save this option as checked then it will store the option as \'on\', otherwise it will be an empty string.
					'id' 			=> 'enable_email_notification_checkbox',
					'label'			=> __( 'E-mail notification', 'test_plugin_text' ),
					'description'		=> __( 'Default is on. Select this option to enable a welcome email notification to new users created by this plugin. ', 'test_plugin_text' ),
					'type'			=> 'checkbox',
					'default'		=> 'on'

Rewriting the CPT Permalink Slug?

Thank you for this plugin template!

I have a question regarding rewrites for the CPT permalink slug. Based on the instructions in your README, I'm adding my arguments to customize my CPT below:

add_filter( 'isi_guide_register_args', 'inquirys_custom_post_filter', 10, 2 );

// Customize post type with {$post_type}_register_args filter
function inquirys_custom_post_filter( $args = array(), $post_type = '' ) {

    // Here are my customizations to the post type
    $args['menu_icon'] = 'dashicons-book-alt';
    $args['labels']['menu_name'] = 'ISI Guide';
    $args['rewrite'] = 'array( \'slug\' => \'implementation-guide-articles\' )';
    return $args;
}

$args['rewrite'] = 'array( \'slug\' => \'implementation-guide-articles\' )';

Yet this function doesn't work. What am I doing incorrectly? Any insights that you could provide would be appreciated.

Quick Edit delete custom fields

I have same custom meta fields that I've enabled for my new post_type.
These work fine as long as I'm using the edit post page. However, when I click "Quick Edit", then click "Update", my custom meta values for the post are deleted.

Test develop branch

Calling all active participants/users of this plugin template.

I've recently merged all PRs that could be merged into the develop branch. Before merging these changes into master, I'd like to have some folks test the plugin template out, to make sure it still works as expected, as well as with the new changes.

If one of your PR's was merged, please do test out your specific change.

Once I have a some feedback on this ticket, I will be able to make a call to merge the changes.

Thank you

Doesn't install in given directory

When I run the shell script, it replaces the template folder with the new plugin files instead of creating them in the given directory. I am on Windows 7 64 bit and the general directory path format I gave is: D:\folder1\folder2\folderr3\plugin-name

What is the correct format of the directory path to use? I have no doubt this is user error. I just need to know what I am doing wrong.

proposal for a universal uninstall script to clean up after plugin is deleted

Hello,
I would like to propose the following uninstall.php

if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

//change your plugin prefix here
delete_options_prefixed( 'test_' );

function delete_options_prefixed( $prefix ) {
    global $wpdb;
    $wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '{$prefix}%'" );
}

How to display html on external pages of the site?

How to display this code on the pages of the site?
echo '<script>alert("'.get_option('wpt_text_block').'");</script>';
How to do it correctly, according to the architecture of this plugin?

I can't understand the structure of the plugin. Do I need to create a file for an external template, or do I need to create a function in the class?
Help me please.

Multi object types and taxonomy edited every where...

I have a taxonomy with multiple object type registered like this:

Cb_Profiler_Client()->register_taxonomy( 'layer-range', 'Layer Range', 'Layer Range', array('user','layer'));

Now when I edit the taxonomy of user id 236 the taxonomy of the layer id 236 is also edited with the same values...

Is it how it is supposed to be?

Metaboxes

Hi hlashbrooke,

I'm trying to use the new admin api for metaboxes, I've only achieved to show the metabox but not the custom fields inside:

in __construct:

add_action( 'add_meta_boxes', array( $this, 'myplugin_add_meta_box' ) );

and the function:

public function myplugin_add_meta_box() {
    $this->admin->add_meta_box(
        $id = 'dmaps_metabox', 
        $title = 'DMaps', 
        $post_types = $screens // array of post types
    );
}

this shows the metabox in the required post types correctly, but what next? how can I put custom fields in the metabox?

thanks in advance :)

upload new image -> javascript error "Uncaught TypeError: Cannot read property 'frames' of undefined"

First let me say thank you for that great template.

However, I discovered that the image upload button threw a javascript error.
So I figured out following this instructions http://kingpro.me/article/tutorials/custom-image-uploader-for-plugins-using-the-wordpress-native-functions/ that I had to simply add
"wp_enqueue_media();" in the public function settings_assets() in file class-wordpress-plugin-template-settings.php.
That helped.
I thought you might want to know about it.

Options prefix should be set at install script

Hi,

First of all, thanks for the fabulous plugin!

Using this boilerplate for the second time, I realized that the options were being set for both plugins at the same time.

Than I found the this line:

should be set to a unique prefix in order to keep the options to the right plugin.

My suggestion is to set the options prefix at the build-plugin script.

Does it make sense? If yes, I would be glad to propose this fix.

best,
alan

Add REST API Support

It would be nice to have the API have an option to enable REST API support, especially since it's become part of core (partly).

For custom post types:

The following could be added after Line 103

'show_in_rest'       => true,
'rest_base'          => $this->post_type,
'rest_controller_class' => 'WP_REST_Posts_Controller',

http://v2.wp-api.org/extending/custom-content-types/#registering-a-custom-post-type-with-rest-api-support

For custom taxonomy:

The following could be added after Line 103

'show_in_rest'       => true,
'rest_base'          => $this->taxonomy,
'rest_controller_class' => 'WP_REST_Terms_Controller',

http://v2.wp-api.org/extending/custom-content-types/#registering-a-custom-taxonomy-with-rest-api-support

Of course, support can be added to existing custom post types via action hook.

 /**
  * Add REST API support to an already registered post type.
  */
  add_action( 'init', 'my_custom_post_type_rest_support', 25 );
  function my_custom_post_type_rest_support() {
    global $wp_post_types;

    //be sure to set this to the name of your post type!
    $post_type_name = 'planet', // where planet is name of the custom post type
    if( isset( $wp_post_types[ $post_type_name ] ) ) {
        $wp_post_types[$post_type_name]->show_in_rest = true;
        $wp_post_types[$post_type_name]->rest_base = $post_type_name;
        $wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';
    }

  }

http://v2.wp-api.org/extending/custom-content-types/#adding-rest-api-support-to-existing-content-types

Default BASE Variable does not work?

"Take note that by default, this plugin is using a prefix of wpt_ before the id that you will be calling, you can override that value by changing it under the __construct function $this->base variable;"

I write the below

$this->base =	'woorocks_';

But it doesn't take any effect, is it wrong of me?

admin->add_meta_boxes()

I'm sure it's me doing something wrong... but I'm a bit confused by this:

In my main plugin file I do:

function yosilose_init() {
    $instance = Yosilose::instance( __FILE__, '1.0.0' );

    if ( is_null( $instance->settings ) ) {
        $instance->settings = Yosilose_Settings::instance( $instance );
    }

    return $instance;
}

$y = yosilose_init();

$y_post = $y->register_post_type(
    'ys_reviews',
    __( 'Reviews', $y->_token ),
    __( 'Review', $y->_token )
);

$y_cats = $y->register_taxonomy(
    'ys_category',
    __('Categories', $y->_token),
    __('Category', $y->_token),
    array($y_post->post_type)
);

$y->admin->add_meta_box(
    $y_post->post_type . '_main_meta',
    __('Various', $y->_token),
    array($y_post->post_type),
    'side',
    'default'
);

But then I get an error about "add_meta_box" not being defined. The call gets to the Admin API and the admin API calls wordpress' version of add_meta_box... but seemingly can't find it in scope.

Which is weird, I can see in the call list that WP is completely loaded by that point:

( ! ) Fatal error: Call to undefined function add_meta_box() in /Users/yivi/Documents/Sites/yosilose-2.0/wp-content/plugins/yosilose/includes/lib/class-yosilose-admin-api.php on line 239
Call Stack
#   Time    Memory  Function    Location
1   0.0238  344440  {main}( )   ../edit.php:0
2   0.0822  403176  require_once( '/Users/yivi/Documents/Sites/yosilose-2.0/wp-admin/admin.php' )   ../edit.php:10
3   0.0825  418488  require_once( '/Users/yivi/Documents/Sites/yosilose-2.0/wp-load.php' )  ../admin.php:31
4   0.0826  428832  require_once( '/Users/yivi/Documents/Sites/yosilose-2.0/wp-config.php' )    ../wp-load.php:29
5   0.0835  509648  require_once( '/Users/yivi/Documents/Sites/yosilose-2.0/wp-settings.php' )  ../wp-config.php:62
6   0.3034  14122096    include_once( '/Users/yivi/Documents/Sites/yosilose-2.0/wp-content/plugins/yosilose/yosilose.php' ) ../wp-settings.php:215
7   0.3093  14424872    Yosilose_Admin_API->add_meta_box( ???, ???, ???, ???, ???, ??? )    ../yosilose.php:64

Shouldn't this work as it is? Again, I feel it's very likely to be user error... but can't understand why it thinks add_meta_box is undefined at that point. :(

Thanks and regards

I not found the name of settings

Dear Hugh
I'm trying to use your plugin

Can you create a small template function where you get the options saved with setting page ?
thanks in advance

wp_localize_script no working.

Hi I just started using this plugin to better organise my code and I think its great but I have a problem. I need the javascript to only load on when the admin page is visible. How do I do this? Like I know all the add_menu_page() code but not sure where to put the wp_enqueue_script and wp_localize_script for ajax to work with this layout.

My current setup is class-name-admin.php

class Name_Admin {
    private $plugin_name;
    // ....

    public function enqueue_scripts() {
        wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'assets/js/name-admin.min.js', array( 'jquery' ), $this->version );
        wp_localize_script($this->plugin_name, $this->plugin_name+"_obj", array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
    }

    public function page_setup(){
        add_menu_page("name", "name", 'manage_options', $this->plugin_name, array( $this, 'show_page'));
    }

    public function show_page(){
       //TODO:  enqueue_scripts to load here
       // $this->enqueue_scripts(); // not working;
       // show_page -> page_setup -> Name::define_admin_hooks -> add_action -> Loader
       echo require "partials/name-admin-page.php"; 
    }
}

And the class-name.php

class Name {
    // ...
    private function define_admin_hooks() {
        $plugin_admin = new Name_Admin( $this->get_plugin_name(), $this->get_version(), $this->loader );
        $this->loader->add_action( 'admin_menu', $plugin_admin, 'page_setup');
    }
}

Metabox example

Can someone please show me an example of how to create a metabox with a custom field using the functions in this template? Are there any plugins which use this template that I can look at? Is there a better place to ask this question?

Fatal Error: Cannot access private property $admin in class-wordpress-plugin-template-settings.php on line 367

Fatal error: Uncaught Error: Cannot access private property WordPress_Plugin_Template::$admin in /app/public/wp-content/plugins/~WordPress-Plugin-Template/includes/class-wordpress-plugin-template-settings.php on line 367

Commenting out line 31 of class-wordpress-plugin-template.php fixes the error.

EDIT: I came up with this fix. Added this to main Class file:

/**
 * Admin function.
 *
 * @var     object
 * @access  public
 * @since   1.0.0
 */
public function admin() {
	$this->admin = $admin;
}

And changed Class _Settings line from this:
array( $this->parent->admin, 'display_field' ),
to this:
array( $this->parent->admin(), 'display_field' ),

Once I figure out how to create a pull request I'll do so.

How to make use of Post_Type class?

Could you please explain how to make use of the inlcluded Post_Type template class?
I don't know where to instanciate the custom post type class of my plugin.

Build script creates 2 directories

When i run the build script from wp-content/plugins I receive two directories of the same destination folder name property resulting in the following structure:

wp-content/plugins/plugin-name/plugin-name 

The build script also doesn't remove the original template plugin as mentioned in the doc. It's possible I'm misunderstanding or executing incorrectly:

Elsie:plugins danieljfris$ bash wordpress-plugin-template/build-plugin.sh
Plugin name: TEST
Destination folder: test
Include Grunt support (y/n): y
Initialise new git repo (y/n): y
Cloning into 'pjaxwp/pjaxwp'...
remote: Counting objects: 282, done.
remote: Total 282 (delta 0), reused 0 (delta 0), pack-reused 282
Receiving objects: 100% (282/282), 101.35 KiB, done.
Resolving deltas: 100% (145/145), done.
Removing git files...
Updating plugin files...
Initialising new git repo...
Initialized empty Git repository in /Users/danieljfris/Sites/Test/wp-content/plugins/test/test/.git/
Complete!

Bug fix plus code enhancements, custom field with type = "color"

Scenario:
Add custom field with type = "color"
Expected:
The field is rendered on the backend and whenever new color is selected the input box value will be updated.
Current Behavior:
The color is selected but the input value remains blank.

File: includes/lib/class-{custom-post}-admin-api.php
Function: display_field()
Section: Get saved data

Fixes plus code enhancements - should replace current lines of 35 to 66:
// Get saved data
$option_name .= $field['id'];
($post) ? $option = get_post_meta( $post->ID, $field['id'], true ) : $option = get_option( $option_name );
if ( isset( $option ) && $option != '' ) {
$data = $option;
} else if(isset($field['default'])){
$data = $field['default'];
} else {
$data = '';
}

Dynamically populate multi-select?

I am not even sure if this is going to be possible, but I would like to dynamically populate a multi select option. The get_race_simple function create a multi-dimensional array which shows up fine in the admin panel, but it wont save anything I select.

            'title'					=> __( 'Map Settings', 'bpc-elections' ),
            'description'			=> __( '<p></p>', 'bpc-elections' ),
            'fields'				=> array(
                array(
                    'id' 			=> 'racemap_selections',
                    'label'			=> __( 'Map Topper', 'bpc-elections' ),
                    'description'	=> __( 'Choose which question are available in the race map.', 'bpc-elections' ),
                    'type'			=> 'checkbox_multi',
                    'options'		=> get_races_simple(),
                )
            )
        );

Build script fails

Tried running the build script, getting an error message:

$ sh build-plugin.sh 
Plugin name: test123
Destination folder: test123
Include Grunt support (y/n): y
Initialise new git repo (y/n): y
build-plugin.sh: 16: build-plugin.sh: Bad substitution

Installer error: "fatal: Too many arguments."

Downloaded the script, made it executable, moved it to /usr/local/bin & ran it. Got error fatal: Too many arguments. Using MacOS Mojave. Other output below:

Removing git files...
rm: README.md: No such file or directory
rm: build-plugin.sh: No such file or directory
rm: changelog.txt: No such file or directory
Updating plugin files...
mv: rename wordpress-plugin-template.php to wp-foft-loader.php: No such file or directory
cp: wp-foft-loader.php: No such file or directory
sed: wp-foft-loader.tmp: No such file or directory
rm: wp-foft-loader.tmp: No such file or directory
cp: readme.txt: No such file or directory
sed: readme.tmp: No such file or directory
rm: readme.tmp: No such file or directory
/usr/local/bin/build.plugin.sh: line 66: cd: lang: No such file or directory
mv: rename wordpress-plugin-template.pot to wp-foft-loader.pot: No such file or directory
cp: wp-foft-loader.pot: No such file or directory
sed: wp-foft-loader.tmp: No such file or directory
rm: wp-foft-loader.tmp: No such file or directory
/usr/local/bin/build.plugin.sh: line 86: cd: ../includes: No such file or directory
mv: rename class-wordpress-plugin-template.php to class-wp-foft-loader.php: No such file or directory
cp: class-wp-foft-loader.php: No such file or directory
sed: class-wp-foft-loader.tmp: No such file or directory
rm: class-wp-foft-loader.tmp: No such file or directory
mv: rename class-wordpress-plugin-template-settings.php to class-wp-foft-loader-settings.php: No such file or directory
cp: class-wp-foft-loader-settings.php: No such file or directory
sed: class-wp-foft-loader-settings.tmp: No such file or directory
rm: class-wp-foft-loader-settings.tmp: No such file or directory
/usr/local/bin/build.plugin.sh: line 117: cd: lib: No such file or directory
mv: rename class-wordpress-plugin-template-post-type.php to class-wp-foft-loader-post-type.php: No such file or directory
cp: class-wp-foft-loader-post-type.php: No such file or directory
sed: class-wp-foft-loader-post-type.tmp: No such file or directory
rm: class-wp-foft-loader-post-type.tmp: No such file or directory
mv: rename class-wordpress-plugin-template-taxonomy.php to class-wp-foft-loader-taxonomy.php: No such file or directory
cp: class-wp-foft-loader-taxonomy.php: No such file or directory
sed: class-wp-foft-loader-taxonomy.tmp: No such file or directory
rm: class-wp-foft-loader-taxonomy.tmp: No such file or directory
mv: rename class-wordpress-plugin-template-admin-api.php to class-wp-foft-loader-admin-api.php: No such file or directory
cp: class-wp-foft-loader-admin-api.php: No such file or directory
sed: class-wp-foft-loader-admin-api.tmp: No such file or directory
rm: class-wp-foft-loader-admin-api.tmp: No such file or directory

Call the options

How can I call the option?
e.g.
array( 'id' => 'radio_buttons', 'label' => __( 'Some Options', 'dvs-scissors' ), 'description' => __( 'A standard set of radio buttons.', 'dvs-scissors' ), 'type' => 'radio', 'options' => array( 'blog' => 'Блог', 'vizitka' => 'Визитка', 'corporate' => 'Корпоративный', 'shop' => 'Магазин' ), 'default' => 'batman' ),
so I want to call two functions with different radio buttons
<?php if( $dvs_settings['radio_buttons'] == 'blog' ) { add_filter('admin_footer_text', 'change_footer_admin'); } elseif( $dvs_settings['radio_buttons'] == 'vizitka' ) { add_action( 'admin_menu', 'my_footer_shh' ); } // end if ?>
What am I doing wrong?

Settings array empty

On init, the instance of this plugin contains the object WordPress_Plugin_Template_Settings, but its field 'settings' is an empty array.
Is it my responsibility to create/load this array with plugin settings or should this happen automagically?

Add Plugin Template Loader

You might want to consider adding a template loader so users can get an idea on how to package templates with a plugin but also allow theme authors to override them. Something along the lines of how woocommerce loads it's templates.

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.