I have a odd problem and i'm hoping one of you could guide me to the answer. I am new to PHP and JQuery, so i'm not really sure what is causing this, but essentially, I have a ajax call for a custom search field that works. The "problem" is that after every search result it returns a very random '0' after the results. So for example if I do a search, i'll get something like:
Stack Overflow 0
I've tried seeing what has caused it in the code but I can't iron it out, and as far as I can tell it just...randomly appears there. I don't mind it showing up, if I had a way to apply a css class to it so I could hide it. Anyways, here's my code:
$args = array(
'role' => 'artist',
'order' => 'ASC',
'orderby' => 'display_name',
'meta_query' => array(
)
);
if (isset($_POST['artistFilter'])){
$name = explode(" ",$_POST['artistFilter']);
$args['meta_query'][] = array(
'key' => 'first_name',
'value' => $name[0],
'compare' => 'LIKE'
);
$args['meta_query'][] = array(
'key' => 'last_name',
'value' => $name[1],
'compare' => 'LIKE'
);
};
if (isset($_POST['mediumType'])){
// WP_User_Query arguments
$args['meta_query'][] = array(
'meta_key' => 'artist_medium',
'value'=> esc_attr($_POST['mediumType']),
'compare' => 'LIKE'
);
};
if (isset($_POST['locationType'])){
$args['meta_query'][] = array(
'meta_key'=>'studio_region_location',
'value' =>$_POST['locationType'],
'compare' => 'LIKE'
);
};
$user_query = new WP_USER_QUERY ($args);
if (! empty($user_query->get_results())){
foreach ($user_query->get_results() as $user){
$artistimage = get_field('primary_image', 'user_' . $user->ID);
echo '<div class="artistSearchColumn">';
if ($artistimage){
echo '<a href="/staging/author/' . esc_html($user->user_login) . '"><img src="' . esc_html($artistimage['url']) . '" alt="Test"/>';
echo '<p>' . $user->first_name. ' ' . $user->last_name .'</p></a>';
}
else {
echo '' . esc_attr($user->first_name) . ' ' . esc_attr($user->last_name) . '';
}
echo '</div>';
}
} else {
echo '<h1>No Users Found.</h1>';
}
my jquery:
<script>
jQuery(function($){
var ajaxscript = {ajax_url: './staging/wp-admin/admin-ajax.php'}
$('#filter').submit(function(){
var filter = $('#filter');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
filter.find('button').text('Finding Artists...'); // changing the button label
},
success:function(data){
alert(data);
filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
</script>
Replacing $('#response').html(data) with anything besides data will not return the 0, so I feel like tis related to that.
Thank you for any help!!!
I figured it out, I have to kill the PHP function manually. I simple added
die();
to the end of the script and it doesn't return the 0. Yay! :)
if (! empty($user_query->get_results())){
foreach ($user_query->get_results() as $user){
$artisttour = get_field('artist_tour_status', 'user_'.$user->ID);
if ($user->artist_profile_display == 'Yes'):
if ($artisttour != 'Not on Tour'):
$artistimage = get_field('primary_image', 'user_' . $user->ID);
echo '<div class="artistSearchColumn">';
if ($artistimage){
echo '<a href="/staging/author/' . esc_html($user->user_login) . '">';
echo '<div class="artistBGImage" style="background: url(' . esc_html($artistimage['url']) .');">';
echo '<img src="https://monadnockart.org/wp-content/plugins/foo/arttour25-2020icon-2.jpg" alt="'.esc_html($user->user_login).'s Artist Profile"/>';
echo '</div>';
echo '<p>' . $user->first_name. ' ' . $user->last_name .'</p>';
echo '</a>';
}
else {
echo '<p>' . esc_attr($user->first_name) . ' ' . esc_attr($user->last_name) . '</p>';
}
echo '</div>';
else:
$artistimage = get_field('primary_image', 'user_' . $user->ID);
echo '<div class="artistSearchColumn">';
if ($artistimage){
echo '<a href="/staging/author/' . esc_html($user->user_login) . '">';
echo '<div class="artistBGImage" style="background: url(' . esc_html($artistimage['url']) .');">';
echo '</div>';
echo '<p>' . $user->first_name. ' ' . $user->last_name .'</p>';
echo '</a>';
}
else {
echo '<p>' . esc_attr($user->first_name) . ' ' . esc_attr($user->last_name) . '</p>';
}
echo '</div>';
endif;
else:
echo '';
endif;
}
}
else {
echo '<h2>No Artists Found.</h2>';
}
die();
}
I'm new to PHP, and I have to edit an existing PHP code for a WordPress plugin to fit my needs.
What I know about hooks is that we can append an extra function inside a function.
But right now I need to edit an entire PHP file, add an extra line of code in the middle of the page.
The problem I'm facing is that the code is not a set of functions for me to use hooks but instead it's like this:
<?php
global $current_user;
master_user_content_block_start(array(
'title' => esc_html__('My Profile', 'master'),
'title-link-text' => esc_html__('Edit Profile', 'master'),
'title-link' => master_get_template_url('user', array('page_type'=>'edit-profile'))
));
$profile_list = array(
'full_name' => esc_html__('Name', 'master'),
'gender' => esc_html__('Gender', 'master'),
'birth_date' => esc_html__('Birth Date', 'master'),
'country' => esc_html__('Country', 'master'),
'email' => esc_html__('Email', 'master'),
'phone' => esc_html__('Phone', 'master'),
'contact_address' => esc_html__('Contact Address', 'master'),
);
echo '<div class="master-my-profile-wrapper" >';
echo '<div class="master-my-profile-avatar" >';
$avatar = get_the_author_meta('master-user-avatar', $current_user->data->ID);
if( !empty($avatar['thumbnail']) ){
echo '<img src="' . esc_url($avatar['thumbnail']) . '" alt="profile-image" />';
}else if( !empty($avatar['file_url']) ){
echo '<img src="' . esc_url($avatar['file_url']) . '" alt="profile-image" />';
}else{
echo get_avatar($current_user->data->ID, 85);
}
echo '</div>';
$even_column = true;
echo '<div class="master-my-profile-info-wrap clearfix" >';
foreach( $profile_list as $meta_field => $field_title ){
$extra_class = 'master-my-profile-info-' . $meta_field;
$extra_class .= ($even_column)? ' master-even': ' master-odd';
echo '<div class="master-my-profile-info ' . esc_attr($extra_class) . ' clearfix" >';
echo '<span class="master-head" >' . $field_title . '</span>';
echo '<span class="master-tail" >';
if( $meta_field == 'birth_date' ){
$user_meta = master_get_user_meta($current_user->data->ID, $meta_field, '-');
if( $user_meta == '-' ){
echo $user_meta;
}else{
echo master_date_format($user_meta);
}
}else if( $meta_field == 'gender' ){
$user_meta = master_get_user_meta($current_user->data->ID, $meta_field, '-');
if( $user_meta == 'male' ){
echo esc_html__('Male', 'master');
}else if( $user_meta == 'female' ){
echo esc_html__('Female', 'master');
}
}else{
echo master_get_user_meta($current_user->data->ID, $meta_field, '-');
}
echo '</span>';
echo '</div>';
$even_column = !$even_column;
}
echo '</div>';
How can I edit the code of this page without changing the main file content using an additional php file to avoide having problems when the plug-in update.
Example of the edit I want to remove the birth date field and change the word Male to adult and Female to child.
I am creating a WordPress using https://github.com/nadeem-khan/WordPress-Plugin-Template as a starter template.
This is my settings class file named 'class-xyz.php':
<?php
if (!defined('ABSPATH'))
exit;
class Xyz_Settings {
/**
* The single instance of Xyz_Settings.
* #var object
* #access private
* #since 1.0.0
*/
private static $_instance = null;
/**
* The main plugin object.
* #var object
* #access public
* #since 1.0.0
*/
public $parent = null;
/**
* Prefix for plugin settings.
* #var string
* #access public
* #since 1.0.0
*/
public $base = '';
/**
* Available settings for plugin.
* #var array
* #access public
* #since 1.0.0
*/
public $settings = array();
public function __construct($parent) {
$this->parent = $parent;
$this->base = 'xyzsms_';
// Initialise settings
add_action('admin_init', array($this, 'init_settings'));
// Register plugin settings
add_action('admin_init', array($this, 'register_settings'));
// Add settings page to menu
add_action('admin_menu', array($this, 'add_menu_item'));
// Add settings link to plugins page
add_filter('plugin_action_links_' . plugin_basename($this->parent->file), array($this, 'add_settings_link'));
}
/**
* Initialise settings
* #return void
*/
public function init_settings() {
$this->settings = $this->settings_fields();
}
/**
* Add settings page to admin menu
* #return void
*/
public function add_menu_item() {
$page = add_options_page(__('XYZ Settings', 'xyz-template'), __('XYZ Settings', 'xyz-template'), 'manage_options', 'xyz_template_settings', array($this, 'settings_page'));
add_action('admin_print_styles-' . $page, array($this, 'settings_assets'));
}
/**
* Load settings JS & CSS
* #return void
*/
public function settings_assets() {
// We're including the farbtastic script & styles here because they're needed for the colour picker
// If you're not including a colour picker field then you can leave these calls out as well as the farbtastic dependency for the wpt-admin-js script below
wp_enqueue_style('farbtastic');
wp_enqueue_script('farbtastic');
// We're including the WP media scripts here because they're needed for the image upload field
// If you're not including an image upload then you can leave this function call out
wp_enqueue_media();
wp_register_script($this->parent->_token . '-settings-js', $this->parent->assets_url . 'js/settings' . $this->parent->script_suffix . '.js', array('farbtastic', 'jquery'), '1.0.0');
wp_enqueue_script($this->parent->_token . '-settings-js');
}
/**
* Add settings link to plugin list table
* #param array $links Existing links
* #return array Modified links
*/
public function add_settings_link($links) {
$settings_link = '' . __('Settings', 'xyz-template') . '';
array_push($links, $settings_link);
return $links;
}
/**
* Build settings fields
* #return array Fields to be displayed on settings page
*/
private function settings_fields() {
$settings['social-bar-position'] = array(
'title' => __('Bar Position', 'xyz-plugin-bar'),
'fields' => array(
array(
'id' => 'xyz_position',
'label' => __('Position', 'xyz-plugin-bar'),
'description' => __('Select the position', 'xyz-plugin-bar'),
'type' => 'radio',
'options' => array('left' => 'Left', 'right' => 'Right'),
'default' => 'left'
),
array(
'id' => 'xyz_margin_top',
'label' => __('Bar Margin Top', 'xyz-plugin-bar'),
'description' => __('Define the margin top', 'xyz-plugin-bar'),
'type' => 'text',
'placeholder' => __('Enter margin.', 'xyz-plugin-bar'),
'default' => '200px'
)
)
);
$settings['social-networks-bar'] = array(
'title' => __('Social Networks', 'xyz-plugin-bar'),
'fields' => array(
array(
'id' => 'xyz_networks',
'label' => __('Social', 'xyz-plugin-bar'),
'description' => __('Select social.', 'xyz-plugin-bar'),
'type' => 'checkbox_multi',
'options' => array(
'facebook' => 'Facebook'
)
)
)
);
$settings['links-bar'] = array(
'title' => __('Links', 'xyz-plugin-bar'),
'description' => __('Enter the Urls for all the selected social networks:', 'xyz-plugin-bar'),
'fields' => array(
array(
'id' => 'facebook_url',
'label' => __('Facebook URL', 'xyz-plugin-bar'),
'description' => __('Enter the URL for Facebook.', 'xyz-plugin-bar'),
'type' => 'text',
'placeholder' => __('Enter Facebook URL', 'xyz-plugin-bar'),
'default' => ''
)
)
);
$settings['custom-classes-bar'] = array(
'title' => __('Custom Classes', 'xyz-plugin-bar'),
'description' => __('Add custom classes in the main parent container of the bar (will affect shortcodes as well):', 'xyz-plugin-bar'),
'fields' => array(
array(
'id' => 'xyz_custom_class',
'label' => __('Add Custom Classes in the Bar Parent Container'),
'description' => __('Add your own custom CSS class (like customclass1 customclass2). Leave empty if default styling is desired.', 'xyz-plugin-bar'),
'type' => 'textarea',
'default' => '',
'placeholder' => __('Add custom classes like .custom_class1 .custom_class2 .custom_class3 to the main container of the social bar.', 'xyz-plugin-bar')
)
)
);
$settings['social-bar-custom-colors'] = array(
'title' => __('Bar Icons Colors', 'xyz-plugin-bar'),
'description' => __('Select the colors', 'xyz-plugin-bar'),
'fields' => array(
array(
'id' => 'bar_facebook_icon_custom_color',
'label' => __('Facebook Icon Color', 'xyz-plugin-bar'),
'description' => __('Default color: #FEFEFE ', 'xyz-plugin-bar'),
'type' => 'color',
'default' => '#FEFEFE'
)
)
);
$settings['add-custom-css-bar'] = array(
'title' => __('Add CSS', 'xyz-plugin-bar'),
'label' => __('Add CSS', 'xyz-plugin-bar'),
'description' => __('Paste your CSS', 'xyz-plugin-bar'),
'fields' => array(
array(
'id' => 'xyz_add_custom_css',
'label' => __('Custom CSS', 'wordpress'),
'description' => __('Do not style', 'xyz-plugin-bar'),
'type' => 'textarea',
'default' => '',
'placeholder' => __('Do not style .', 'xyz-plugin-bar')
)
)
);
$settings = apply_filters('xyz_fields', $settings);
return $settings;
}
/**
* Register plugin settings
* #return void
*/
public function register_settings() {
if (is_array($this->settings)) {
foreach ($this->settings as $section => $data) {
// Add section to page
add_settings_section($section, $data['title'], array($this, 'settings_section'), 'xyz_template_settings');
foreach ($data['fields'] as $field) {
// Validation callback for field
$validation = '';
if (isset($field['callback'])) {
$validation = $field['callback'];
}
// Register field
$option_name = $this->base . $field['id'];
register_setting('xyz_template_settings', $option_name, $validation);
// Add field to page
add_settings_field($field['id'], $field['label'], array($this, 'display_field'), 'xyz_template_settings', $section, array('field' => $field));
}
}
}
}
public function settings_section($section) {
$html = '<p> ' . $this->settings[$section['id']]['description'] . '</p>' . "\n";
echo $html;
}
/**
* Generate HTML for displaying fields
* #param array $args Field data
* #return void
*/
public function display_field($args) {
$field = $args['field'];
$html = '';
$option_name = $this->base . $field['id'];
$option = get_option($option_name);
$data = '';
if (isset($field['default'])) {
$data = $field['default'];
if ($option) {
$data = $option;
}
}
switch ($field['type']) {
case 'text':
case 'password':
case 'number':
$html .= '<input id="' . esc_attr($field['id']) . '" type="' . $field['type'] . '" name="' . esc_attr($option_name) . '" placeholder="' . esc_attr($field['placeholder']) . '" value="' . $data . '"/>' . "\n";
break;
case 'text_secret':
$html .= '<input id="' . esc_attr($field['id']) . '" type="text" name="' . esc_attr($option_name) . '" placeholder="' . esc_attr($field['placeholder']) . '" value=""/>' . "\n";
break;
case 'textarea':
$html .= '<textarea id="' . esc_attr($field['id']) . '" rows="5" cols="50" name="' . esc_attr($option_name) . '" placeholder="' . esc_attr($field['placeholder']) . '">' . $data . '</textarea><br/>' . "\n";
break;
case 'checkbox':
$checked = '';
if ($option && 'on' == $option) {
$checked = 'checked="checked"';
}
$html .= '<input id="' . esc_attr($field['id']) . '" type="' . $field['type'] . '" name="' . esc_attr($option_name) . '" ' . $checked . '/>' . "\n";
break;
case 'checkbox_multi':
foreach ($field['options'] as $k => $v) {
$checked = false;
if (in_array($k, $data)) {
$checked = true;
}
$html .= '<label for="' . esc_attr($field['id'] . '_' . $k) . '"><input type="checkbox" ' . checked($checked, true, false) . ' name="' . esc_attr($option_name) . '[]" value="' . esc_attr($k) . '" id="' . esc_attr($field['id'] . '_' . $k) . '" /> ' . $v . '</label> ';
}
break;
case 'radio':
foreach ($field['options'] as $k => $v) {
$checked = false;
if ($k == $data) {
$checked = true;
}
$html .= '<label for="' . esc_attr($field['id'] . '_' . $k) . '"><input type="radio" ' . checked($checked, true, false) . ' name="' . esc_attr($option_name) . '" value="' . esc_attr($k) . '" id="' . esc_attr($field['id'] . '_' . $k) . '" /> ' . $v . '</label> ';
}
break;
case 'select':
$html .= '<select name="' . esc_attr($option_name) . '" id="' . esc_attr($field['id']) . '">';
foreach ($field['options'] as $k => $v) {
$selected = false;
if ($k == $data) {
$selected = true;
}
$html .= '<option ' . selected($selected, true, false) . ' value="' . esc_attr($k) . '">' . $v . '</option>';
}
$html .= '</select> ';
break;
case 'select_multi':
$html .= '<select name="' . esc_attr($option_name) . '[]" id="' . esc_attr($field['id']) . '" multiple="multiple">';
foreach ($field['options'] as $k => $v) {
$selected = false;
if (in_array($k, $data)) {
$selected = true;
}
$html .= '<option ' . selected($selected, true, false) . ' value="' . esc_attr($k) . '" />' . $v . '</label> ';
}
$html .= '</select> ';
break;
case 'image':
$image_thumb = '';
if ($data) {
$image_thumb = wp_get_attachment_thumb_url($data);
}
$html .= '<img id="' . $option_name . '_preview" class="image_preview" src="' . $image_thumb . '" /><br/>' . "\n";
$html .= '<input id="' . $option_name . '_button" type="button" data-uploader_title="' . __('Upload an image', 'xyz-template') . '" data-uploader_button_text="' . __('Use image', 'xyz-template') . '" class="image_upload_button button" value="' . __('Upload new image', 'xyz-template') . '" />' . "\n";
$html .= '<input id="' . $option_name . '_delete" type="button" class="image_delete_button button" value="' . __('Remove image', 'xyz-template') . '" />' . "\n";
$html .= '<input id="' . $option_name . '" class="image_data_field" type="hidden" name="' . $option_name . '" value="' . $data . '"/><br/>' . "\n";
break;
case 'color':
?><div class="color-picker" style="position:relative;">
<input type="text" name="<?php esc_attr_e($option_name); ?>" class="color" value="<?php esc_attr_e($data); ?>" />
<div style="position:absolute;background:#FFF;z-index:99;border-radius:100%;" class="colorpicker"></div>
</div>
<?php
break;
}
switch ($field['type']) {
case 'checkbox_multi':
case 'radio':
case 'select_multi':
$html .= '<br/><span class="description">' . $field['description'] . '</span>';
break;
default:
$html .= '<label for="' . esc_attr($field['id']) . '"><span class="description">' . $field['description'] . '</span></label>' . "\n";
break;
}
echo $html;
}
/**
* Validate individual settings field
* #param string $data Inputted value
* #return string Validated value
*/
public function validate_field($data) {
if ($data && strlen($data) > 0 && $data != '') {
$data = urlencode(strtolower(str_replace(' ', '-', $data)));
}
return $data;
}
/**
* Load settings page content
* #return void
*/
public function settings_page() {
// Build page HTML
$html = '<div class="wrap" id="xyz_settings">' . "\n";
$html .= '<h2>' . __('XYZ Settings', 'xyz-template') . '</h2>' . "\n";
$html .= '<form method="post" action="options.php" enctype="multipart/form-data">' . "\n";
// Setup navigation
$html .= '<ul id="settings-sections" class="subsubsub hide-if-no-js">' . "\n";
$html .= '<li><a class="tab all current" href="#all">' . __('All', 'xyz-template') . '</a></li>' . "\n";
foreach ($this->settings as $section => $data) {
$html .= '<li>| <a class="tab" href="#' . $section . '">' . $data['title'] . '</a></li>' . "\n";
}
$html .= '</ul>' . "\n";
$html .= '<div class="clear"></div>' . "\n";
// Get settings fields
ob_start();
settings_fields('xyz_template_settings');
do_settings_sections('xyz_template_settings');
$html .= ob_get_clean();
$html .= '<p class="submit">' . "\n";
$html .= '<input name="Submit" type="submit" class="button-primary" value="' . esc_attr(__('Save Settings', 'xyz-template')) . '" />' . "\n";
$html .= '</p>' . "\n";
$html .= '</form>' . "\n";
$html .= '</div>' . "\n";
echo $html;
}
/**
* Main Xyz_Settings Instance
*
* Ensures only one instance of Xyz_Settings is loaded or can be loaded.
*
* #since 1.0.0
* #static
* #see Xyz()
* #return Main Xyz_Settings instance
*/
public static function instance($parent) {
if (is_null(self::$_instance)) {
self::$_instance = new self($parent);
}
return self::$_instance;
}
// End instance()
/**
* Cloning is forbidden.
*
* #since 1.0.0
*/
public function __clone() {
_doing_it_wrong(__FUNCTION__, __('Cheatin’ huh?'), $this->parent->_version);
}
// End __clone()
/**
* Unserializing instances of this class is forbidden.
*
* #since 1.0.0
*/
public function __wakeup() {
_doing_it_wrong(__FUNCTION__, __('Cheatin’ huh?'), $this->parent->_version);
}
// End __wakeup()
}
All the settings fields are displayed properly but as soon as the submit button is pressed 404 is generated and no settings get saved. What am I missing here?
UPDATE: Here's how the initialize Xyz_Settings class is initialized in another file:
function Xyz_bar_init () {
$instance = Xyz_bar::instance( __FILE__, '1.0.0' );
if( is_null( $instance->settings ) ) {
$instance->settings = Xyz_Settings::instance( $instance );
}
return $instance;
}
Xyz_bar_init();
UPDATE(2): I have activated a very trimmed down version of my own plugin with only 2-3 settings options and it seems to work perfectly (as values are getting saved/retrieved in the db correctly). Can the shear number of setting options be causing the issue with the full fledge plugin that has over 200 options (please note that I am using a shared hosting with limited resources)?
If you are saving a large number of options, make sure you don't saturate the max_input_vars limit, that was introduced in PHP 5.3.9 to limit the number of accepted input variables - from the PHP docs:
How many input variables may be accepted (limit is applied to $_GET,
$_POST and $_COOKIE superglobal separately). Use of this directive
mitigates the possibility of denial of service attacks which use hash
collisions.
You should be able to modify this value to your needs in php.ini.
Also remember to check your error logs.
I have Make changes in this file and now post are showing :- class-wordpress-plugin-template-post_type.php
your code :-
// Post type name and labels
$this->post_type = 'post_type';
$this->plural = _x( 'Posts', 'post type general name' , 'wordpress-plugin-template' );
$this->single = _x( 'Post', 'post type singular name' , 'wordpress-plugin-template' );
My code :-
// Post type name and labels
$this->post_type = 'post_type1'; // change your value here
$this->plural = _x( 'Your Posts', 'post type general name' , 'wordpress-plugin-template' );
$this->single = _x( 'Post', 'post type singular name' , 'wordpress-plugin-template' );
Go to admin/permalinks and simply save your setting again, no need to change anything. 9 out of 10 this will fix the 404 problem after adding custom settings (same for custom templates).
You can also add 'flush_rewrite_rules();' at the end of your construct function to avoid this step.
[Edit]
Ok, now that out the way... your forms action points to simply "options.php". This means your plugin will look in the plugin or root folder for options.php. It should be site_url()."/wp-admin/options.php".
I have a theme options page and a loop which grabs my categories. This code works fine and I am able to save my options. The code like this:
function drop_elements_function(){
$my_cats = get_categories();
$i = 1;
foreach( $my_cats as $my_cat ) :
$my_categories[$my_cat->cat_ID] = array(
'value' => $my_cat->cat_ID,
'label' => $my_cat->cat_name
);
$i++;
endforeach;
$options = get_option('sandbox_theme_social_options');
echo'<select id="featured_cat" name="sandbox_theme_social_options[Drop_Elements]">';
foreach ( $my_categories as $category ){
$label = $category['label'];
$selected = '';
if ( $options['Drop_Elements'] == $category['value'] )
$selected = 'selected="selected"';
echo '<option style="padding-right: 10px;" value="' . esc_attr( $category['value'] ) . '" ' . $selected . '>' . $label . '</option>';
}
echo '</select>';
//print_r($options['Drop_Elements']);
}/*Function end*/
The output looks like this:
http://www.vasinternetposao.com/img.png
Problem: Now when my theme is installed for the first time i am getting the output like the screen shot above but obviously my option is not yet saved to the database (user must click the save button in order to select that category). So i was thinking to do something like this:
1.) User install the theme for the first time and then output looks like this:
http://www.vasinternetposao.com/img2.png
2.) If user unintentionally select "Choose your category" and clicks the "save button"
the output will be again:
http://www.vasinternetposao.com/img2.png
3.) If the user select the real category (not "Choose Your Category") then "Choose Your Category" Disappears:
http://www.vasinternetposao.com/img.png
This is my attempt but it is not working:
function drop_elements_function(){
$my_cats = get_categories();
$i = 1;
foreach( $my_cats as $my_cat ) :
$my_categories[$my_cat->cat_ID] = array(
'value' => $my_cat->cat_ID,
'label' => $my_cat->cat_name
);
$i++;
endforeach;
$options = get_option('sandbox_theme_social_options');
echo'<select id="featured_cat" name="sandbox_theme_social_options[Drop_Elements]">';
foreach ( $my_categories as $category ){
$label = $category['label'];
$selected = '';
if ( $options['Drop_Elements'] == $category['value'] ){
$selected = 'selected="selected"';
echo '<option style="padding-right: 10px;" value="' . esc_attr( $category['value'] ) . '" ' . $selected . '>' . $label . '</option>';
}
elseif(!isset($options['Drop_Elements'])){
$selected = 'selected="selected"';
echo '<option selected="selected" value="Choose Your Category">Choose Your Category</option>';
echo '<option style="padding-right: 10px;" value="' . esc_attr( $category['value'] ) . '" ' . '>' . $label . '</option>';
}
}/*Foreach close*/
echo '</select>';
//print_r($options['Drop_Elements']);
}/*Function end*/
Can it be done with PHP? Any help is appreciated! Thank you!
I think what you want to do is something like the following example:
echo '<select id="featured_cat" name="sandbox_theme_social_options[Drop_Elements]">';
echo '<option selected="selected" value="Choose Your Category">Choose Your Category</option>';
foreach ( $my_categories as $category ){
$label = $category['label'];
$selected = ( $options['Drop_Elements'] == $category['value'] ) ? " selected='selected' " : "";
echo '<option style="padding-right: 10px;" value="' . esc_attr( $category['value'] ) . '" ' . $selected . '>' . $label . '</option>';
}
echo "</select>";
I am trying to write a content rating script where the user can select what type of rating to give to their article (for instance, what age group the articles suits for).
I am using a Wordpress star rating script as a template.
This part of the script is where the user selects the rating:
function pn_apr_meta_box_form( $post )
{
wp_nonce_field( 'pn_apr_meta_box_nonce', 'pn_apr_meta_box_nonce_field' );
$current_post_rating = get_post_meta( $post->ID, PN_APR_RATING_META_KEY, true );
echo '<label for="pn_apr_rating">' . __( 'Choose a rating for this post:', 'author-post-ratings' ) . '</label> ';
echo '<select name="pn_apr_rating" id="pn_apr_rating">';
echo '<option value="unrated"' . selected( $current_post_rating, 0, false ) . '>' . __( 'Unrated', 'author-post-ratings' ) . '</option>';
for ( $i = 1; $i <= 5; $i++ ) {
echo '<option value="' . $i . '"' . selected( $current_post_rating, $i, false ) . '>' . sprintf( _n( '%1s Star', '%1s Stars', $i, 'author-post-ratings' ), $i ) . '</option>';
}
echo '</select>';
}
This part of the script outputs the ratings:
if ( $rating ) {
$output = null;
$output .= '<div class="author-post-rating">';
$output .= '<span class="author-post-rating-label">' . esc_attr( $pn_apr_settings['label_text'] ) . '</span> ';
$output .= '<span class="author-post-rating-stars" title="' . sprintf( __( '%1$d out of %2$d stars', 'author-post-ratings' ), $rating, 5 ) . '">';
// Output active stars
for ( $i = 1; $i <= $rating; $i++ ) {
$output .= '<img src="' . PN_APR_PLUGIN_DIR_URL . 'images/star-active.png" />';
}
// Output inactive stars
for ( $i = $rating + 1; $i <= 5; $i++ ) {
$output .= '<img src="' . PN_APR_PLUGIN_DIR_URL . 'images/star-inactive.png" />';
}
$output .= '</span>' . "\n";
$output .= '</div><!-- .author-post-rating -->';
if ( true == $return ) { return $output; }
// We don't need to use "else" here, since calling return will automatically stop further execution of this function.
echo $output;
}
Now, I want to change this script so that it becomes a content rating script (rather than star rating one). I want to offer these choices for the user:
G — Suitable for all audiences
PG — Possibly offensive, usually for audiences 13 and above
R — Intended for adult audiences above 17
X — Even more mature than above
Question: How can I change the script so that if the user selects for instance PG, then it will output the text Suitable for age 13 and up.
EDIT:
To Shawn, observe the following code:
function rating_select_cb( $post ) {
global $wpdb;
$value = get_post_meta($post->ID, 'rating', true);
echo '<div class="misc-pub-section misc-pub-section-last"><span id="timestamp"><label>Select a rating:<br></label>';
// build an array of each available rating
$ratings = array(
1 => 'G — Suitable for all audiences',
2 => 'PG — Possibly offensive, usually for audiences 13 and above',
3 => 'R — Intended for adult audiences above 17',
4 => 'X — Even more mature than above'
);
echo '<select name="rating">';
echo '<option value=""' . ((($value == '') || !isset($ratings[$value])) ? ' selected="selected"' : '') . '> None... </option>';
// output each rating as an option
foreach ($ratings as $id => $text) {
echo '<option value="' . $id . '"' . (($value == $id) ? ' selected="selected"' : '') . '">' . $text. '</option>';
}
echo '</select>';
echo '</span></div>';
}
Here's something that should get you to where you need to be:
Add to your functions.php:
add_action( 'add_meta_boxes', 'rating_select_box' );
function rating_select_box() {
add_meta_box(
'rating_select_box', // id, used as the html id att
__( 'Select rating:' ), // meta box title, like "Page Attributes"
'rating_select_cb', // callback function, spits out the content
'post', // post type or page. We'll add this to posts only
'side', // context (where on the screen
'low' // priority, where should this go in the context?
);
}
function rating_select_cb( $post )
{
global $wpdb;
$value = get_post_meta($post->ID, 'rating', true);
echo '<div class="misc-pub-section misc-pub-section-last">
<span id="timestamp">'
. '<label>Select a rating:<br></label>';
$selected = ($value == $result->post_name) ? ' selected="selected" ' : null;
echo '<select name="rating">';
echo '<option value="" default="default"> None... </option>';
echo '<option value="0" '.$selected.'> G — Suitable for all audiences </option>';
echo '<option value="1" '.$selected.'> PG — Possibly offensive, usually for audiences 13 and above </option>';
echo '<option value="2" '.$selected.'> R — Intended for adult audiences above 17 </option>';
echo '<option value="3" '.$selected.'> X — Even more mature than above </option>';
echo '</select>';
echo '</span></div>';
}
add_action( 'save_post', 'save_metadata');
function save_metadata($postid)
{
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return false;
if ( !current_user_can( 'edit_page', $postid ) ) return false;
if( empty($postid) ) return false;
if ( is_null($_REQUEST["rating"]) ) {
delete_post_meta($postid, 'rating');
} else {
update_post_meta($postid, 'rating', $_REQUEST['rating']);
}
}
The above code does this:
1. Adds a new metabox to your posts
2. Adds a select box with the rating values
3. Saves the metadata with the post
To access your metadata in your templates:
$meta = get_post_custom($post->ID);
echo $meta['rating'][0];
To have your template display a custom string use something like:
switch ( $meta['rating'][0] ) {
case 0:
echo "This is rated PG";
break;
case 1:
echo "This is rated G";
break;
case 2:
echo "This is rated R";
break;
case 3:
echo "Ug oh! This is rated X!";
break;
default:
echo "This is not yet rated.";
}
**Edit: This code provides full functionality.. you could abandon your current solution if it works for you