WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Image deleted regardless if checkbox is checked or not (7 posts)

  1. Nerina-01
    Member
    Posted 1 year ago #

    Hello,

    I have a problem I'm trying to solve, but with no avail because php is really not my field. I already searched the forums and found a few solutions to similar problems, but I couldn't get the to work.

    I created a Theme Options Page where you can for ex. upload a Logo to be used on the Website. I created a check box and want to delete the logo if the check box is checked. Anyway, the logo is deleted when I click Save changes, but regardless if I checked the check box or not.

    This is my code:

    // LOGO
    function logo_setting() {
    	$options = get_option('theme_options');
    	if (empty($options['logo'])) :
    		$options['logo'] = '';
    	else :
        	echo "<img src='{$options['logo']}' width='205px' /><br>";
    
    		//DELETE OPTION
    		if (!isset( $options['del_logo'] ) ) :
    				$options['del_logo'] = '';
    				echo "<br>Remove logo?&nbsp;";
    				?> <input type="checkbox" id="del_logo" name="theme_options[del_logo]" value="1" <?php checked( true, $options['del_logo'] ); ?> /><?php
    
    				echo "<br>If logo is removed, Site Title will be used.";
    			else :
    				$options = get_option('theme_options');
    				$options['logo'] = '';
    				update_option('theme_options', $options);
    				echo "Logo removed";
    		endif;
    		$options['del_logo'] = ( $options['del_logo'] == 1 ? 1 : 0 );
    		return $options;
    
    	endif;
    	echo "<input type='file' name='logo' />";
    }

    I hope someone can explain to me what I'm doing wrong and how I should do it properly. Please have in mind that I'm an almost absolute php beginner.

  2. bcworkz
    Member
    Posted 1 year ago #

    You are sort of using two options (logo and del_logo) to manage one state by whether one or the other is empty or not. This could work, but it is needlessly complicated and prone to error.

    You only need one option to manage this aspect, let's use 'del_logo'. If it's value is false, display the logo. If it is true, do not display the logo. The option value will be based on the checkbox state. The 'logo' image source value can be considered semi-static and unimportant for the question at hand. (Though you do need to ensure it exists before trying to use it) Also, a small quibble, you use the term 'remove', which I find confusing, as you are not actually removing the image file from the server, you are simply removing (needlessly) the path reference.

    Mind you, I see no need to actually remove the file or it's reference, I just find the terminology confusing. A checkbox labeled 'Hide Logo' would suffice for me.

    Since you only provided a snippet, it's not clear how you are handling the form submit. One thing though, this is not the place to be using update_option() because you do not know the current form state yet, you are acting on old information. You should review the Settings API for how to handle settings forms.

  3. Nerina-01
    Member
    Posted 1 year ago #

    Thank you bcworkz for answering, and thank you for explaining it to me.

    I've went trough:
    http://codex.wordpress.org/Settings_API
    and one more time trough:
    http://codex.wordpress.org/Function_Reference/checked
    http://codex.wordpress.org/Creating_Options_Pages
    and as recommended by the WP Codex:
    http://ottopress.com/2009/wordpress-settings-api-tutorial/

    Call me stupid, but I can't get this to work. I think I have a moderate understanding of the links above, but obviously I don't know/understand some important things. At this moment I have this:

    function logo_setting() {
    	$options = get_option('theme_options');
    	if (1 !== $options['logo']) :
    		$options['logo'] = '';
    		echo "don't show logo<br>";
    	else :
        	echo "<img src='{$options['logo']}' width='205px' /><br>";
    		echo '<br>Remove logo? <input name="theme_options[logo]" id="page_logo" type="checkbox" value="1" ' . checked( 1, $options['logo'], false ) . ' /> <br>If logo is removed, Site Title will be used.';
    	endif;
    	echo "<input type='file' name='logo' />";
    }

    Now it doesn't show at all. And I don't understand why. The problem is also that I don't know how to do the following:

    The option value will be based on the checkbox state.

    Below is more than just this snippet:

    <?php
    // Call and create Options page
    add_action('admin_menu', 'theme_menu');
    
    function theme_menu() {
    	add_menu_page('Theme Options', 'Theme Options', 'administrator', __FILE__, 'theme_options');
    } 
    
    function theme_options() {?>
    	<div id="theme_options_header" class="wrap">
            <div id="icon-themes" class="icon32"><br /></div>
            <h2>Theme Options</h2><br />
            <p>Some description</p>
        </div>
        <div id="theme_options" class="widefat">
         	<form method="post" action="options.php" enctype="multipart/form-data">
            <?php settings_fields('theme_options'); ?>
            <?php do_settings_sections(__FILE__); ?>
                <p class="submit">
                    <input name="Submit" type="submit" class="button-primary" value="<?php esc_attr_e('Save Changes'); ?>" />
                </p>
            </form>
        </div>
    <?php }
    
    add_action('admin_init', 'register_settings');
    
    function register_settings() {
    	register_setting('theme_options', 'theme_options', 'validate_setting');
    	add_settings_section('main_section', 'Main Settings', 'section_cb', __FILE__);
    
    	add_settings_field('logo', 'Logo', 'logo_setting', __FILE__, 'main_section');
    }
    
    ///////////////////////////////////////////////// LOGO
    function logo_setting() {
    	$options = get_option('theme_options');
    	if (1 !== $options['logo']) :
    		$options['logo'] = '';
    		echo "don't show logo<br>";
    	else :
        	echo "<img src='{$options['logo']}' width='205px' /><br>";
    		echo '<br>Remove logo? <input name="theme_options[logo]" id="page_logo" type="checkbox" value="1" ' . checked( 1, $options['logo'], false ) . ' /> <br>If logo is removed, Site Title will be used.';
    	endif;
    	echo "<input type='file' name='logo' />";
    }
    
    function section_cb() {}
    function validate_setting($theme_options) {
    	//echo '<pre>'; print_r($theme_options); die();
    	$keys = array_keys($_FILES);
    	$i = 0;
    	foreach ($_FILES as $image) {
    		if ($image['size']) {
    			if (preg_match('/(jpg|jpeg|png|gif)$/', $image['type'])) {
    				$override = array('welcome_form' => false, 'test_form' => false);
    				$file = wp_handle_upload($image, $override);
    				$theme_options[$keys[$i]] = $file['url'];
    			 } else {
    				$options = get_option('theme_options');
    				$theme_options[$keys[$i]] = $options[$logo];
    				wp_die('No image was uploaded.');
    			 }
    		}
    		else {
    			$options = get_option('theme_options');
    			$theme_options[$keys[$i]] = $options[$keys[$i]];
    		}
    		$i++;
    	}
    	return $theme_options;
    }
    add_action('admin_head', 'admin_register_head');
    function admin_register_head() {
    	$url = get_bloginfo('template_directory') . '/includes/options_page.css';
    	echo "<link rel='stylesheet' href='$url' />\n";
    }
    ?>
  4. bcworkz
    Member
    Posted 1 year ago #

    You've made some good progress there, despite it not working. I certainly would not call you stupid. Naive perhaps, but not stupid :) I think the reason nothing is showing is you are trying to do too much with the callback for add_settings_field(). The callback is meant to only output the one form element related to the setting. You are trying to populate the whole section with it.

    I suggest taking a step back and focusing on the single checkbox setting. Hardcode the image source for now, and don't worry about whether the graphic shows on the settings page or not. Add this stuff back in once the checkbox bit is straight and the setting impacts the front end properly.

    As for "The option value will be based on the checkbox state." The settings API should save something in the options table based on whether the checkbox is checked or not. Whatever it is, it should be keyed to the form element name. I don't really know exactly what the API does with checkboxes, you'll need to experiment.

    Anyway, ultimately, on your front end templates, there will be a conditional if block based on this option value, whatever it is. If it's one value, the logo is displayed, otherwise nothing is displayed. I hope this gets you pointed in the right direction. I also hope you're finding some enjoyment out of all this despite the frustration.

  5. Nerina-01
    Member
    Posted 1 year ago #

    Thank you again for taking the time. Much as it is frustrating, it is a great sense of accomplishment when you finally understand. I think I gained some insight from your answer, although due to holidays in my timezone I wasn't able to work on the problem, but I will certainly post the solution here when and if I find it.

    "Call me stupid" is an idiom, and you shouldn't take that literally. I also don't find it amusing that you call me naive. This is not meant in an aggressive manner bcworkz, I appreciate your time and effort very much.

  6. bcworkz
    Member
    Posted 1 year ago #

    I also don't find it amusing that you call me naive. This is not meant in an aggressive manner bcworkz

    Despite you having no aggressive intent, I'm a sorry you took offense at my comment, none was intended. Chalk it up to miscommunication by strangers from different cultures.

    I'm pleased I was able to otherwise help, that is reward enough for me.

  7. Nerina-01
    Member
    Posted 1 year ago #

    At last a success :) This is how I got it working:

    function logo_setting() {
    	$options = get_option('theme_options');
    	if (empty($options['logo'])) :
    		$options['logo'] = '';
    		echo "Site title is used.<br>";
    	else :
        	echo "<img src='{$options['logo']}' width='205px' /><br>";
    	endif;
    	echo "<input type='file' name='logo' />";
    
    	if (empty($options['hide_logo'])) :
    		$options['hide_logo'] = '';
    	endif;
    	echo '<br><br>Show site title instead of logo? <input name="theme_options[hide_logo]" id="hide_logo" type="checkbox" value="1" ' . checked( 1, $options['hide_logo'], false ) . ' />';
    }

    And in the html:

    <?php if (empty($options['logo']) || isset($options['hide_logo'])) :
                                bloginfo('name');
                            else : ?>
                                <img src="<?php echo $options['logo']; ?>" alt="Logo" />
                            <?php endif; ?>

    bcworkz, if you didn't intend to offense me, than no offense taken. Thank you very much for helping, and for making me think about the code from different perspectives. As a designer I'm used to another kind of thinking schemes.

Topic Closed

This topic has been closed to new replies.

About this Topic