• I’m relatively new to coding, I know the concept of a lot of WordPress functions/actions etc.

    I’m building my own plug-in just for my own use and for learning.

    I have the the plug-in working in the sense I have it displaying and installing correctly in the back end.. but what I want to do is once a check box has been checked, to do an action, which is to include a file from the same plugin dir /src/somefile.php

    The section at the bottom that I’ve commented out isn’t working, I’ve lost my train of thought and just can’t figure it out.

    Here’s my code:

    <?php
    /*
    	Plugin Name: Custom Functionality Plugin
    	Description: enable/disable site specific functions
    	Author: damion Founde
    	Version: 1.0.0
    */
    class Custom_Functions_Plugin {
    
        public function __construct() {
        	// Hook into the admin menu
        	add_action( 'admin_menu', array( $this, 'create_plugin_settings_page' ) );
    
            // Add Settings and Fields
        	add_action( 'admin_init', array( $this, 'setup_sections' ) );
        	add_action( 'admin_init', array( $this, 'setup_fields' ) );
        }
    
        public function create_plugin_settings_page() {
        	// Add the menu item and page
        	$page_title = 'Funconality Plugin';
        	$menu_title = 'Functions Plugin';
        	$capability = 'manage_options';
        	$slug = 'custom_functionality';
        	$callback = array( $this, 'plugin_settings_page_content' );
        	$icon = 'dashicons-admin-plugins';
        	$position = 100;
    
        	add_menu_page( $page_title, $menu_title, $capability, $slug, $callback, $icon, $position );
        }
    
        public function plugin_settings_page_content() {?>
        	<div class="wrap">
        		<h2>Functionality Plugin</h2><?php
                if ( isset( $_GET['settings-updated'] ) && $_GET['settings-updated'] ){
                      $this->admin_notice();
                } ?>
        		<form method="POST" action="options.php">
                    <?php
                        settings_fields( 'cf_fields' );
                        do_settings_sections( 'cf_fields' );
                        submit_button();
                    ?>
        		</form>
        	</div> <?php
        }
        
        public function admin_notice() { ?>
            <div class="notice notice-success is-dismissible">
                <p>Your settings have been updated!</p>
            </div><?php
        }
    
        public function setup_sections() {
            add_settings_section( 'css_scripts_section', 'CSS and Scripts', array( $this, 'section_callback' ), 'cf_fields' );
            add_settings_section( 'frontend_section', 'Front End Functions', array( $this, 'section_callback' ), 'cf_fields' );
            add_settings_section( 'backend_section', 'Back End Functions', array( $this, 'section_callback' ), 'cf_fields' );
        }
    
        public function section_callback( $arguments ) {
        	switch( $arguments['id'] ){
        		case 'css_scripts_section':
        			echo 'These functions will enqueue css and/or scripts';
        			break;
        		case 'frontend_section':
        			echo 'These Functions will modify how the end user sees features';
        			break;
        		case 'backend_section':
        			echo 'These Functions will modify features/aspects of the admin section.';
        			break;
        	}
        }
    
        public function setup_fields() {
            $fields = array(
    
            	array(
            		'uid' => 'cf_script_checkboxes',
            		'label' => 'Functions:',
            		'section' => 'css_scripts_section',
            		'type' => 'checkbox',
            		'options' => array(
            			'option1' => 'Option 1',
            			'option2' => 'Option 2',
            			'option3' => 'Option 3',
            			'option4' => 'Option 4',
            			'option5' => 'Option 5',
            		),
                    'default' => array()
            	),
              array(
            		'uid' => 'cf_fe_heckboxes',
            		'label' => 'Functions:',
            		'section' => 'frontend_section',
            		'type' => 'checkbox',
            		'options' => array(
            			'option1' => 'Option 1',
            			'option2' => 'Option 2',
            			'option3' => 'Option 3',
            			'option4' => 'Option 4',
            			'option5' => 'Option 5',
            		),
                    'default' => array()
            	),
              array(
            		'uid' => 'cf_be_checkboxes',
            		'label' => 'Functions:',
            		'section' => 'backend_section',
            		'type' => 'checkbox',
            		'options' => array(
            			'option1' => 'Option 1',
            			'option2' => 'Option 2',
            			'option3' => 'Option 3',
            			'option4' => 'Option 4',
            			'option5' => 'Option 5',
            		),
                    'default' => array()
            	),
              
              
            );
        	foreach( $fields as $field ){
    
            	add_settings_field( $field['uid'], $field['label'], array( $this, 'field_callback' ), 'cf_fields', $field['section'], $field );
                register_setting( 'cf_fields', $field['uid'] );
        	}
        }
    
        public function field_callback( $arguments ) {
    
            $value = get_option( $arguments['uid'] );
    
            if( ! $value ) {
                $value = $arguments['default'];
            }
    
            switch( $arguments['type'] ){
              
                case 'checkbox':
                    if( ! empty ( $arguments['options'] ) && is_array( $arguments['options'] ) ){
                        $options_markup = '';
                        $iterator = 0;
                        foreach( $arguments['options'] as $key => $label ){
                            $iterator++;
                            $options_markup .= sprintf( '<label for="%1$s_%6$s"><input id="%1$s_%6$s" name="%1$s[]" type="%2$s" value="%3$s" %4$s /> %5$s</label><br/>', $arguments['uid'], $arguments['type'], $key, checked( $value[ array_search( $key, $value, true ) ], $key, false ), $label, $iterator );
                        }
                        printf( '<fieldset>%s</fieldset>', $options_markup );
                    }
                    break;
            }
    
            if( $helper = $arguments['helper'] ){
                printf( '<span class="helper"> %s</span>', $helper );
            }
    
            if( $supplimental = $arguments['supplimental'] ){
                printf( '<p class="description">%s</p>', $supplimental );
            }
    
        }
    
    }
    /*add_action('init', 'nd_handle_cb');
    function nd_handle_cb() {
      $options = get_option( $arguments['cf_checkboxes'] );
    
    get_option( $arguments['cf_checkboxes']);
    if ( $options['option1'] == '1' ) {
        //do something
    }
    
    else { 
          //do nothing
      }
      return;
    }
    */
    new Custom_Functions_Plugin();
Viewing 4 replies - 1 through 4 (of 4 total)
  • This code can cause a problem

           $value = get_option( $arguments['uid'] );
            if( ! $value ) {
                $value = $arguments['default'];
            }

    because the the saved value could be falsy (0 or ” or null).
    You can do this:
    $value = get_option( $arguments['uid'], $arguments['default'] );

    If all your options are checkboxes, you don’t need a switch statement.

    For the last part, you need to write functions to do the things your options enable. So for loading a CSS or script file, you write a function that is hooked to the script enqueue (for either front end or admin), and in that function you check the option before doing it.
    It’s reverse of the code you started with (and can’t figure out)… you don’t go through the option array, you write functions for each option and hook them in the appropriate place for that option. Some options might be in the same function if they would be in the same hook anyway (like enqueuing scripts and styles).

    Thread Starter dfounde

    (@dfounde)

    Thanks for replying..

    I think I understand what your saying.
    Initially there was going to be a a couple of text boxes. As good practice is it worth leaving the switch in just in case I add other field types?

    With regard to the code you indicated as an issue should I replace with your suggested code?

    The final part… I have basic functions in separate files that do stuff like enqueue scripts, I was wanting to say if option one in the css_scripts_section was tick to include the function file ‘enqueue-scripts.php’. Is that not possible or am I making a hash of it?

    How do I go about doing the if statement?

    Should I include each function inside my plugin file?

    I’m keen to understand the right way to do it with visual examples so I can learn from it.

    Thanks for your help

    Good practice is to write for what you are doing, instead of generic. ??
    And yes, I would use the arguments of get_option as intended rather than an obvious problem with an if statement. But the logic seems faulty anyway. A form with a checkbox only contains the data for the checked checkboxes. The unchecked ones are not part of the data. The value you retrieve from the database could be 0, to indicate it is “off”, and you don’t want the default value if so. The second parameter of get_option is only used when the option itself isn’t found. With yours being in an array (which is best practice), you can’t actually use get_option with a single checkbox name. (Your code is kind of confusing… I’ve done one thing with the Settings API, long ago.)

    I don’t see any advantage to adding 3 sections, all using the same callback, which you then have to use a switch statement to separate them out. I would make 3 functions.

    For your separate files: if you already coded the functions I suggested, to handle each option, that code would include the add_action calls to hook the functions where they are needed. You can simply require those files. Or if some are admin only, put the require in an if ( is_admin() ) check. Your files should only be loaded when they are needed, not on every admin page or front end page.

    Thread Starter dfounde

    (@dfounde)

    Ok thanks. Back to the drawing board I think.

    I think I’ve over complicated my understanding and learning.

    Thanks for your help

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Include file if checkbox is checked’ is closed to new replies.