I just finished my theme today and included theme settings page with css.php file where I can change the site colors from panel.
in header I added
<link rel='stylesheet' type='text/css' href="<?php bloginfo('template_directory'); ?>/css/style.php" />
But I want to use it with if else
for example
if theme is installed and doesnt have changes in theme settings
display
<link rel='stylesheet' type='text/css' href="<?php bloginfo('template_directory'); ?>/css/style.css" /> css file
But when theme has changes in theme settings page eliminate first css file and display
<link rel='stylesheet' type='text/css' href="<?php bloginfo('template_directory'); ?>/css/style.php" />
Is this possible?
All you need to do is add a flag to theme-settings save action.
For example :
1: In your plugin or theme functions.php
add_action( 'optionsframework_after_validate', function(){ // this action is not real, you need to change it to your code
update_option( 'theme-settings-changed', 'changed' );
});
2: In your theme header file
$change_check = get_option( 'theme-settings-changed' );
if ( $change_check == 'changed' ) {
?>
<link rel='stylesheet' type='text/css' href="<?php bloginfo('template_directory'); ?>/css/style.php" />
<?php
} else {
?>
<link rel='stylesheet' type='text/css' href="<?php bloginfo('template_directory'); ?>/css/style.css" />
<?php
}
This approach doesn't guarantee if the setting is 'actually' changed because it just checks if the save button is fired regardless of setting changes. But it's a safe bet that the save button would be fired when an user changed a value.
If that's not enough, you can add a check logic for that purpose though it's going to be tedious.
function optionsframework_option_name() {
// This gets the theme name from the stylesheet
$themename = wp_get_theme();
$themename = preg_replace("/\W/", "_", strtolower($themename) );
$optionsframework_settings = get_option( 'optionsframework' );
$optionsframework_settings['id'] = $themename;
update_option( 'optionsframework', $optionsframework_settings );
}
/**
* Defines an array of options that will be used to generate the settings page and be saved in the database.
* When creating the 'id' fields, make sure to use all lowercase and no spaces.
*
* If you are making your theme translatable, you should replace 'test'
* with the actual text domain for your theme. Read more:
* http://codex.wordpress.org/Function_Reference/load_theme_textdomain
*/
function optionsframework_options() {
$options = array();
$imagepath = get_template_directory_uri() . '/images/';
$true_false = array(
'true' => __('true', 'test'),
'false' => __('false', 'test')
);
$options[] = array(
'name' => __('General', 'test'),
'type' => 'heading');
$options[] = array(
'name' => __('Site Links', 'test'),
'desc' => __('Site Links color', 'test'),
'id' => 'links',
'std' => '',
'class' => '',
'type' => 'color');
$options[] = array(
'name' => __('Site Links Hover', 'test'),
'desc' => __('Site Links Hover color', 'test'),
'id' => 'hover',
'std' => '',
'class' => '',
'type' => 'color');
$options[] = array(
'name' => __('Background Color', 'test'),
'desc' => __('background color', 'test'),
'id' => 'bg',
'std' => '',
'class' => '',
'type' => 'color');
return $options;
}
<?php
add_action( 'init', 'optionsframework_rolescheck' );
function optionsframework_rolescheck () {
if ( current_user_can( 'edit_theme_options' ) ) {
// If the user can edit theme options, let the fun begin!
add_action( 'admin_menu', 'optionsframework_add_page');
add_action( 'admin_init', 'optionsframework_init' );
add_action( 'wp_before_admin_bar_render', 'optionsframework_adminbar' );
}
}
/* Loads the file for option sanitization */
add_action( 'init', 'optionsframework_load_sanitization' );
function optionsframework_load_sanitization() {
require_once dirname( __FILE__ ) . '/options-sanitize.php';
}
/*
* Creates the settings in the database by looping through the array
* we supplied in options.php. This is a neat way to do it since
* we won't have to save settings for headers, descriptions, or arguments.
*
* Read more about the Settings API in the WordPress codex:
* http://codex.wordpress.org/Settings_API
*
*/
function optionsframework_init() {
// Include the required files
require_once dirname( __FILE__ ) . '/options-interface.php';
require_once dirname( __FILE__ ) . '/options-media-uploader.php';
// Optionally Loads the options file from the theme
$location = apply_filters( 'options_framework_location', array( 'options.php' ) );
$optionsfile = locate_template( $location );
// Load settings
$optionsframework_settings = get_option('optionsframework' );
// Updates the unique option id in the database if it has changed
if ( function_exists( 'optionsframework_option_name' ) ) {
optionsframework_option_name();
}
elseif ( has_action( 'optionsframework_option_name' ) ) {
do_action( 'optionsframework_option_name' );
}
// If the developer hasn't explicitly set an option id, we'll use a default
else {
$default_themename = get_option( 'stylesheet' );
$default_themename = preg_replace("/\W/", "_", strtolower($default_themename) );
$default_themename = 'optionsframework_' . $default_themename;
if ( isset( $optionsframework_settings['id'] ) ) {
if ( $optionsframework_settings['id'] == $default_themename ) {
// All good, using default theme id
} else {
$optionsframework_settings['id'] = $default_themename;
update_option( 'optionsframework', $optionsframework_settings );
}
}
else {
$optionsframework_settings['id'] = $default_themename;
update_option( 'optionsframework', $optionsframework_settings );
}
}
// If the option has no saved data, load the defaults
if ( ! get_option( $optionsframework_settings['id'] ) ) {
optionsframework_setdefaults();
}
// Registers the settings fields and callback
register_setting( 'optionsframework', $optionsframework_settings['id'], 'optionsframework_validate' );
// Change the capability required to save the 'optionsframework' options group.
add_filter( 'option_page_capability_optionsframework', 'optionsframework_page_capability' );
}
/**
* Ensures that a user with the 'edit_theme_options' capability can actually set the options
* See: http://core.trac.wordpress.org/ticket/14365
*
* #param string $capability The capability used for the page, which is manage_options by default.
* #return string The capability to actually use.
*/
function optionsframework_page_capability( $capability ) {
return 'edit_theme_options';
}
/*
* Adds default options to the database if they aren't already present.
* May update this later to load only on plugin activation, or theme
* activation since most people won't be editing the options.php
* on a regular basis.
*
* http://codex.wordpress.org/Function_Reference/add_option
*
*/
function optionsframework_setdefaults() {
$optionsframework_settings = get_option( 'optionsframework' );
// Gets the unique option id
$option_name = $optionsframework_settings['id'];
/*
* Each theme will hopefully have a unique id, and all of its options saved
* as a separate option set. We need to track all of these option sets so
* it can be easily deleted if someone wishes to remove the plugin and
* its associated data. No need to clutter the database.
*
*/
if ( isset( $optionsframework_settings['knownoptions'] ) ) {
$knownoptions = $optionsframework_settings['knownoptions'];
if ( !in_array( $option_name, $knownoptions ) ) {
array_push( $knownoptions, $option_name );
$optionsframework_settings['knownoptions'] = $knownoptions;
update_option( 'optionsframework', $optionsframework_settings );
}
} else {
$newoptionname = array( $option_name );
$optionsframework_settings['knownoptions'] = $newoptionname;
update_option( 'optionsframework', $optionsframework_settings );
}
// Gets the default options data from the array in options.php
$options =& _optionsframework_options();
// If the options haven't been added to the database yet, they are added now
$values = of_get_default_values();
if ( isset( $values ) ) {
add_option( $option_name, $values ); // Add option with default settings
}
}
function optionsframework_menu_settings() {
$menu = array(
'page_title' => __( 'test Theme Options', 'optionsframework'),
'menu_title' => __('test Settings', 'optionsframework'),
'capability' => 'edit_theme_options',
'menu_slug' => 'test-options',
'callback' => 'optionsframework_page'
);
return apply_filters( 'optionsframework_menu', $menu );
}
/* Add a subpage called "Theme Options" to the appearance menu. */
function optionsframework_add_page() {
$menu = optionsframework_menu_settings();
$of_page = add_theme_page( $menu['page_title'], $menu['menu_title'], $menu['capability'], $menu['menu_slug'], $menu['callback'] );
// Load the required CSS and javscript
add_action( 'admin_enqueue_scripts', 'optionsframework_load_scripts' );
add_action( 'admin_print_styles-' . $of_page, 'optionsframework_load_styles' );
}
/* Loads the CSS */
function optionsframework_load_styles() {
wp_enqueue_style( 'optionsframework', OPTIONS_FRAMEWORK_DIRECTORY.'css/optionsframework.css' );
if ( !wp_style_is( 'wp-color-picker','registered' ) ) {
wp_register_style( 'wp-color-picker', OPTIONS_FRAMEWORK_DIRECTORY.'css/color-picker.min.css' );
}
wp_enqueue_style( 'wp-color-picker' );
}
/* Loads the javascript */
function optionsframework_load_scripts( $hook ) {
$menu = optionsframework_menu_settings();
if ( 'appearance_page_' . $menu['menu_slug'] != $hook )
return;
// Enqueue colorpicker scripts for versions below 3.5 for compatibility
if ( !wp_script_is( 'wp-color-picker', 'registered' ) ) {
wp_enqueue_script( 'iris', false, array( 'jquery','jquery-ui-draggable', 'jquery-ui-slider', 'jquery-touch-punch' ), false, 1 );
wp_register_script( 'wp-color-picker', OPTIONS_FRAMEWORK_DIRECTORY . 'js/color-picker.min.js', array( 'jquery', 'iris' ) );
$colorpicker_l10n = array(
'clear' => __( 'Clear','options_framework_theme' ),
'defaultString' => __( 'Default', 'options_framework_theme' ),
'pick' => __( 'Select Color', 'options_framework_theme' )
);
wp_localize_script( 'wp-color-picker', 'wpColorPickerL10n', $colorpicker_l10n );
}
// Enqueue custom option panel JS
wp_enqueue_script( 'options-custom', OPTIONS_FRAMEWORK_DIRECTORY . 'js/options-custom.js', array( 'jquery','wp-color-picker' ) );
// Inline scripts from options-interface.php
add_action( 'admin_head', 'of_admin_head' );
}
function of_admin_head() {
// Hook to add custom scripts
do_action( 'optionsframework_custom_scripts' );
}
/*
* Builds out the options panel.
*
* If we were using the Settings API as it was likely intended we would use
* do_settings_sections here. But as we don't want the settings wrapped in a table,
* we'll call our own custom optionsframework_fields. See options-interface.php
* for specifics on how each individual field is generated.
*
* Nonces are provided using the settings_fields()
*
*/
if ( !function_exists( 'optionsframework_page' ) ) :
function optionsframework_page() {
settings_errors(); ?>
<div id="optionsframework-wrap" class="wrap">
<?php screen_icon( 'themes' ); ?>
<h2 class="nav-tab-wrapper">
<?php echo optionsframework_tabs(); ?>
</h2>
<div id="optionsframework-metabox" class="metabox-holder">
<div id="optionsframework" class="postbox">
<form action="options.php" method="post">
<?php settings_fields( 'optionsframework' ); ?>
<?php optionsframework_fields(); /* Settings */ ?>
<div id="optionsframework-submit">
<input type="submit" class="button-primary" name="update" value="<?php esc_attr_e( 'Save Options', 'options_framework_theme' ); ?>" />
<input type="submit" class="reset-button button-secondary" name="reset" value="<?php esc_attr_e( 'Restore Defaults', 'options_framework_theme' ); ?>" onclick="return confirm( '<?php print esc_js( __( 'Click OK to reset. Any theme settings will be lost!', 'options_framework_theme' ) ); ?>' );" />
<div class="clear"></div>
</div>
</form>
</div> <!-- / #container -->
</div>
<?php do_action( 'optionsframework_after' ); ?>
</div> <!-- / .wrap -->
<?php
}
endif;
/**
* Validate Options.
*
* This runs after the submit/reset button has been clicked and
* validates the inputs.
*
* #uses $_POST['reset'] to restore default options
*/
function optionsframework_validate( $input ) {
/*
* Restore Defaults.
*
* In the event that the user clicked the "Restore Defaults"
* button, the options defined in the theme's options.php
* file will be added to the option for the active theme.
*/
if ( isset( $_POST['reset'] ) ) {
add_settings_error( 'options-framework', 'restore_defaults', __( 'Default options restored.', 'options_framework_theme' ), 'updated fade' );
return of_get_default_values();
}
/*
* Update Settings
*
* This used to check for $_POST['update'], but has been updated
* to be compatible with the theme customizer introduced in WordPress 3.4
*/
$clean = array();
$options =& _optionsframework_options();
foreach ( $options as $option ) {
if ( ! isset( $option['id'] ) ) {
continue;
}
if ( ! isset( $option['type'] ) ) {
continue;
}
$id = preg_replace( '/[^a-zA-Z0-9._\-]/', '', strtolower( $option['id'] ) );
// Set checkbox to false if it wasn't sent in the $_POST
if ( 'checkbox' == $option['type'] && ! isset( $input[$id] ) ) {
$input[$id] = false;
}
// Set each item in the multicheck to false if it wasn't sent in the $_POST
if ( 'multicheck' == $option['type'] && ! isset( $input[$id] ) ) {
foreach ( $option['options'] as $key => $value ) {
$input[$id][$key] = false;
}
}
// For a value to be submitted to database it must pass through a sanitization filter
if ( has_filter( 'of_sanitize_' . $option['type'] ) ) {
$clean[$id] = apply_filters( 'of_sanitize_' . $option['type'], $input[$id], $option );
}
}
// Hook to run after validation
do_action( 'optionsframework_after_validate', $clean );
return $clean;
}
/**
* Display message when options have been saved
*/
function optionsframework_save_options_notice() {
add_settings_error( 'options-framework', 'save_options', __( 'Options saved.', 'options_framework_theme' ), 'updated fade' );
}
add_action( 'optionsframework_after_validate', 'optionsframework_save_options_notice' );
/**
* Format Configuration Array.
*
* Get an array of all default values as set in
* options.php. The 'id','std' and 'type' keys need
* to be defined in the configuration array. In the
* event that these keys are not present the option
* will not be included in this function's output.
*
* #return array Rey-keyed options configuration array.
*
* #access private
*/
function of_get_default_values() {
$output = array();
$config =& _optionsframework_options();
foreach ( (array) $config as $option ) {
if ( ! isset( $option['id'] ) ) {
continue;
}
if ( ! isset( $option['std'] ) ) {
continue;
}
if ( ! isset( $option['type'] ) ) {
continue;
}
if ( has_filter( 'of_sanitize_' . $option['type'] ) ) {
$output[$option['id']] = apply_filters( 'of_sanitize_' . $option['type'], $option['std'], $option );
}
}
return $output;
}
/**
* Add Theme Options menu item to Admin Bar.
*/
function &_optionsframework_options() {
static $options = null;
if ( !$options ) {
// Load options from options.php file (if it exists)
$location = apply_filters( 'options_framework_location', array('options.php') );
if ( $optionsfile = locate_template( $location ) ) {
$maybe_options = require_once $optionsfile;
if ( is_array($maybe_options) ) {
$options = $maybe_options;
} else if ( function_exists( 'optionsframework_options' ) ) {
$options = optionsframework_options();
}
}
// Allow setting/manipulating options via filters
$options = apply_filters('of_options', $options);
}
return $options;
}
/**
* Get Option.
*
* Helper function to return the theme option value.
* If no value has been saved, it returns $default.
* Needed because options are saved as serialized strings.
*/
if ( ! function_exists( 'of_get_option' ) ) {
function of_get_option( $name, $default = false ) {
$config = get_option( 'optionsframework' );
if ( ! isset( $config['id'] ) ) {
return $default;
}
$options = get_option( $config['id'] );
if ( isset( $options[$name] ) ) {
return $options[$name];
}
return $default;
}
}
Related
Recently I made a custom shortcode that displays the Dokan "Add Product" form, but now every time I add a new product I get redirected to the Product edit page in the Dokan dashboard. My php skills are very limited as this is the 1st time iv'e ever done any coding but I get stuff fast.
Can someone help me with this issue?
This is the end of the code that the shortcode displays (after the submit button).
</form>
<?php } else { ?>
<?php dokan_seller_not_enabled_notice(); ?>
<?php } ?>
<?php } else { ?>
<?php do_action( 'dokan_can_post_notice' ); ?>
<?php } ?>
</div>
<?php
/**
* dokan_after_new_product_inside_content_area hook
*
* #since 2.4
*/
do_action( 'dokan_after_new_product_inside_content_area' );
?>
</div> <!-- #primary .content-area -->
<?php
/**
* dokan_dashboard_content_after hook
* dokan_after_new_product_content_area hook
*
* #since 2.4
*/
do_action( 'dokan_dashboard_content_after' );
do_action( 'dokan_after_new_product_content_area' );
?>
Add this code to functions.php of your child theme.
At first, we remove default ajax action, then add our custom action with the same function, but with modified $redirect value.
if ( wp_doing_ajax() ) {
remove_action( 'wp_ajax_dokan_create_new_product', array( 'WeDevs\Dokan\Ajax', 'create_product' ) );
add_action( 'wp_ajax_dokan_create_new_product', 'dokan_ajax_create_product' );
}
function dokan_ajax_create_product() {
check_ajax_referer( 'dokan_reviews' );
if ( ! current_user_can( 'dokan_add_product' ) ) {
wp_send_json_error( __( 'You have no permission to do this action', 'dokan-lite' ) );
}
$submited_data = isset( $_POST['postdata'] ) ? wp_unslash( $_POST['postdata'] ) : ''; //phpcs:ignore
parse_str( $submited_data, $postdata );
$response = dokan_save_product( $postdata );
if ( is_wp_error( $response ) ) {
wp_send_json_error( $response->get_error_message() );
}
if ( is_int( $response ) ) {
/* if ( current_user_can( 'dokan_edit_product' ) ) {
$redirect = dokan_edit_product_url( $response );
} else { */
$redirect = dokan_get_navigation_url( 'products' );
/* } */
wp_send_json_success( $redirect );
} else {
wp_send_json_error( __( 'Something wrong, please try again later', 'dokan-lite' ) );
}
}
And, for non-ajax requests:
add_action( 'dokan_add_new_product_redirect', 'custom_dokan_add_new_product_redirect', 10, 2 );
function custom_dokan_add_new_product_redirect( $redirect, $product_id ) {
$redirect = dokan_get_navigation_url( 'products' );
return $redirect;
}
With the new version of Dokan, you can adjust this in file dokan-lite/includes/Dashboard/Templates with the code above!
Edit this file public_html/wp-content/plugins/dokan-lite/classes/template-products.php
do_action( 'dokan_new_product_added', $product_id, $post_data );
if ( current_user_can( 'dokan_edit_product' ) ) {
$redirect = dokan_edit_product_url( $product_id );
} else {
$redirect = dokan_get_navigation_url( 'products' );
}
Just replace the value for $redirect with your custom url like below
$redirect = ("https://www.wordpress.com/dashboard/products/");
For redirection after Edit product page replace the same below
do_action( 'dokan_product_updated', $post_id );
//$edit_url = dokan_edit_product_url( $post_id );
$redirect = apply_filters( 'dokan_add_new_product_redirect', dokan_edit_product_url( $post_id ), $post_id );
wp_redirect( add_query_arg( array( 'message' => 'success' ), $redirect ) );
exit;
Hello guys i got new WP theme and i cant install im getting this error on website
Parse error: syntax error, unexpected '}', expecting end of file in
/storage/h3/665/790665/public_html/wp-content/themes/gameaddict/post_templates.php
on line 1
<?php
class Single_Post_Template_Plugin {
function __construct() {
add_action( 'admin_menu', array( $this, 'add_metabox' ) );
add_action( 'save_post', array( $this, 'metabox_save' ), 1, 2 );
add_filter( 'single_template', array( $this, 'get_post_template' ) );
}
function get_post_template( $template ) {
global $post;
$custom_field = get_post_meta( $post->ID, '_wp_post_template', true );
if( !$custom_field )
return $template;
/** Prevent directory traversal */
$custom_field = str_replace( '..', '', $custom_field );
if( file_exists( get_stylesheet_directory() . "/{$custom_field}" ) )
$template = get_stylesheet_directory() . "/{$custom_field}";
elseif( file_exists( get_template_directory() . "/{$custom_field}" ) )
$template = get_template_directory() . "/{$custom_field}";
return $template;
}
function get_post_templates() {
$templates = wp_get_theme()->get_files( 'php', 1 );
$post_templates = array();
$base = array( trailingslashit( get_template_directory()), trailingslashit( get_stylesheet_directory()) );
foreach ( (array) $templates as $file => $full_path ) {
if( $full_path == get_theme_root().'/gameaddict/post_templates.php'){continue;}else{
if ( !preg_match( '|Single Post Template:(.*)$|mi', file_get_contents( $full_path ), $header ))
continue;
$post_templates[ $file ] = _cleanup_header_comment( $header[1] );
}}
return $post_templates;
}
function post_templates_dropdown() {
global $post;
$post_templates = $this->get_post_templates();
/** Loop through templates, make them options */
foreach ( (array) $post_templates as $template_file => $template_name ) {
$selected = ( $template_file == get_post_meta( $post->ID, '_wp_post_template', true ) ) ? ' selected="selected"' : '';
$opt = '<option value="' . esc_attr( $template_file ) . '"' . $selected . '>' . esc_html( $template_name ) . '</option>';
echo $opt;
}
}
function add_metabox() {
$screens = array( 'post', 'portfolio' );
foreach ( $screens as $screen ) {
add_meta_box(
'pt_post_templates',
__( 'Sidebar position', 'addict' ),
array( $this, 'metabox' ),
$screen,'normal', 'high'
);
}
}
function metabox( $post ) {
?>
<input type="hidden" name="pt_noncename" id="pt_noncename" value="<?php echo wp_create_nonce( plugin_basename( __FILE__ ) ); ?>" />
<label class="hidden" for="post_template"><?php _e( 'Post Template', 'addict' ); ?></label><br />
<select name="_wp_post_template" id="post_template" class="dropdown">
<?php $this->post_templates_dropdown(); ?>
</select>
<?php
}
function metabox_save( $post_id, $post ) {
/*
* Verify this came from the our screen and with proper authorization,
* because save_post can be triggered at other times
*/
if(isset($_POST['pt_noncename'])){
if ( !wp_verify_nonce( $_POST['pt_noncename'], plugin_basename( __FILE__ ) ) )
return $post->ID;
}
/** Is the user allowed to edit the post or page? */
if(isset($_POST['post_type'])){
if ( 'page' == $_POST['post_type'] )
if ( !current_user_can( 'edit_page', $post->ID ) )
return $post->ID;
else
if ( !current_user_can( 'edit_post', $post->ID ) )
return $post->ID;
}
/** OK, we're authenticated: we need to find and save the data */
/** Put the data into an array to make it easier to loop though and save */
if(isset($_POST['_wp_post_template'])){
$mydata['_wp_post_template'] = $_POST['_wp_post_template'];
}
/** Add values of $mydata as custom fields */
if(isset($mydata)){
foreach ( $mydata as $key => $value ) {
/** Don't store custom data twice */
if( 'revision' == $post->post_type )
return;
/** If $value is an array, make it a CSV (unlikely) */
$value = implode( ',', (array) $value );
/** Update the data if it exists, or add it if it doesn't */
if( get_post_meta( $post->ID, $key, false ) )
update_post_meta( $post->ID, $key, $value );
else
add_post_meta( $post->ID, $key, $value );
/** Delete if blank */
if( !$value )
delete_post_meta( $post->ID, $key );
}}
}
}
add_action( 'init', 'post_templates_plugin_init' );
/**
* Instantiate the class after theme has been set up.
*/
function post_templates_plugin_init() {
new Single_Post_Template_Plugin;
}
Assuming the theme is this one https://themeforest.net/item/game-addict-clan-war-gaming-theme/6771881 and it's purchased from themeforest, it should work right out of the box. Try downloading it again, make sure to check if there is not a zipped file inside of the zip you are downloading to make sure you are uploading the right file, sometimes the zip you download has a lot of files like documentation and demos, but the actual theme file is another zip inside.
If nothing of the above helps, write to their customer support.
Basically, it's complaining that wp-content/themes/gameaddict/post_templates.php has a } on line 1, while PHP was expecting end of a file. The code you've included seems fine. The issue is most likely about the developer closing a bracket without opening it, somewhere in the code. It seems like you're using a pre-made theme, in that case contacting the developer would be the best option.
I've to create some product filters for my WP site. I found this PHP script:
$GLOBALS['my_query_filters'] = array(
'field_1' => 'forma',
'field_2' => 'posa',
'field_3' => 'conduttore',
'field_4' => 'isolante',
'field_5' => 'raggio_minimo_di_curvatura',
'field_6' => 'guaina',
'field_7' => 'marchiatura',
'field_8' => 'tensione_di_esercizio',
'field_9' => 'temp_max_esercizio',
'field_10' => 'temp_min_di_inst',
'field_11' => 'temp_max_corto'
);
// action
add_action('pre_get_posts', 'my_pre_get_posts', 10, 1);
function my_pre_get_posts( $query ) {
// bail early if is in admin
if( is_admin() ) {
return;
}
// get meta query
$meta_query = $query->get('meta_query');
// loop over filters
foreach( $GLOBALS['my_query_filters'] as $key => $name ) {
// continue if not found in url
if( empty($_GET[ $name ]) ) {
continue;
}
// get the value for this filter
// eg: http://www.website.com/events?city=melbourne,sydney
$value = explode(',', $_GET[ $name ]);
// append meta query
$meta_query[] = array(
'key' => $name,
'value' => $value,
'compare' => 'IN',
);
}
// update meta query
$query->set('meta_query', $meta_query);
}
where $GLOBALS['my_query_filters'] is created by me following the found directions. I inserted this code into function.php file.
This is the shop page code:
<?php
/**
* The Template for displaying product archives, including the main shop page which is a post type archive
*
* This template can be overridden by copying it to yourtheme/woocommerce/archive-product.php.
*
* HOWEVER, on occasion WooCommerce will need to update template files and you
* (the theme developer) will need to copy the new files to your theme to
* maintain compatibility. We try to do this as little as possible, but it does
* happen. When this occurs the version of the template file will be bumped and
* the readme will list any important changes.
*
* #see https://docs.woocommerce.com/document/template-structure/
* #author WooThemes
* #package WooCommerce/Templates
* #version 2.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
get_header( 'shop' ); ?>
<?php
/**
* woocommerce_before_main_content hook.
*
* #hooked woocommerce_output_content_wrapper - 10 (outputs opening divs for the content)
* #hooked woocommerce_breadcrumb - 20
*/
do_action( 'woocommerce_before_main_content' );
?>
<?php if ( apply_filters( 'woocommerce_show_page_title', true ) ) : ?>
<h1 class="page-title"><?php woocommerce_page_title(); ?></h1>
<?php endif; ?>
<div id="archive-filters">
<?php foreach( $GLOBALS['my_query_filters'] as $key => $name ):
// get the field's settings without attempting to load a value
$field = get_field_object($key, false, false);
// set value if available
if( isset($_GET[ $name ]) ) {
$field['value'] = explode(',', $_GET[ $name ]);
}
// create filter
?>
<div class="filter" data-filter="<?php echo $name; ?>">
<?php create_field( $field ); ?>
</div>
<?php endforeach; ?>
</div>
<script type="text/javascript">
(function($) {
// change
$('#archive-filters').on('change', 'input[type="checkbox"]', function(){
// vars
var url = '<?php echo home_url('property'); ?>';
args = {};
// loop over filters
$('#archive-filters .filter').each(function(){
// vars
var filter = $(this).data('filter'),
vals = [];
// find checked inputs
$(this).find('input:checked').each(function(){
vals.push( $(this).val() );
});
// append to args
args[ filter ] = vals.join(',');
});
// update url
url += '?';
// loop over args
$.each(args, function( name, value ){
url += name + '=' + value + '&';
});
// remove last &
url = url.slice(0, -1);
// reload page
window.location.replace( url );
});
})(jQuery);
</script>
<?php
/**
* woocommerce_archive_description hook.
*
* #hooked woocommerce_taxonomy_archive_description - 10
* #hooked woocommerce_product_archive_description - 10
*/
do_action( 'woocommerce_archive_description' );
?>
<?php if ( have_posts() ) : ?>
<?php
/**
* woocommerce_before_shop_loop hook.
*
* #hooked woocommerce_result_count - 20
* #hooked woocommerce_catalog_ordering - 30
*/
do_action( 'woocommerce_before_shop_loop' );
?>
<?php woocommerce_product_loop_start(); ?>
<?php woocommerce_product_subcategories(); ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php
/**
* woocommerce_after_shop_loop hook.
*
* #hooked woocommerce_pagination - 10
*/
do_action( 'woocommerce_after_shop_loop' );
?>
<?php elseif ( ! woocommerce_product_subcategories( array( 'before' => woocommerce_product_loop_start( false ), 'after' => woocommerce_product_loop_end( false ) ) ) ) : ?>
<?php wc_get_template( 'loop/no-products-found.php' ); ?>
<?php endif; ?>
<?php
/**
* woocommerce_after_main_content hook.
*
* #hooked woocommerce_output_content_wrapper_end - 10 (outputs closing divs for the content)
*/
do_action( 'woocommerce_after_main_content' );
?>
<?php
/**
* woocommerce_sidebar hook.
*
* #hooked woocommerce_get_sidebar - 10
*/
do_action( 'woocommerce_sidebar' );
?>
<?php get_footer( 'shop' ); ?>
The result in only that in the shop page there are ten empty rows (the same filters number inserted into the array) but other nothing happens.
How can I completed the filters creation?
Can I add add a relation between your meta_query expects nested arrays?
Can you help me, please?
Thanks!
Maybe you can change some things with the foreach loop and var names.
I rewrite my_pre_get_posts() :
function my_pre_get_posts( $query ) {
// bail early if is in admin
if( is_admin() || !is_main_query() ) {
return;
}
// get meta query
$meta_query = $query->get('meta_query');
$meta_queries = array();
foreach( $GLOBALS['my_query_filters'] as $key => $name ) {
// continue if not found in url
if( empty($_GET[ $name ]) ) {
continue;
}
$value = explode(',', $_GET[ $name ]);
$meta_queries[] = array(
'key' => $name,
'value' => $value,
'compare' => 'IN',
);
}
$meta_query = array(
'relation' => 'AND',
$meta_queries
);
// update meta query
$query->set('meta_query', $meta_query);
}
Here $meta_queries is append to the nested array that $meta_query expect.
In the function I didn't care about $meta_query = $query->get('meta_query');.
Hope it helps.
Try this:
function my_pre_get_posts( $query ) {
// bail early if is in admin
if( is_admin() || !is_main_query() ) {
return;
}
// get meta query
$meta_queries = $query->get('meta_query');
foreach( $GLOBALS['my_query_filters'] as $key => $name ) {
// continue if not found in url
if( empty($_GET[ $name ]) ) {
continue;
}
$value = explode(',', $_GET[ $name ]);
$meta_queries[] = array(
'key' => $name,
'value' => $value,
'compare' => 'IN',
);
}
$meta_query = array(
'relation' => 'AND',
$meta_queries
);
// update meta query
$query->set('meta_query', $meta_query);
}
It is an external group blogs plugin
It gives group creators and administrators on your BuddyPress install the ability to attach external blog RSS feeds to groups.
Blog posts will appear within the activity stream for the group.
New posts will automatically be pulled every hour, or every 30 minutes if someone specifically visits a group page.
There are so many bugs that I found.
1) it is not fetching feeds automatically
2) if I try to manually updates feeds it is reposting the same entries, I mean it is not fetching new feeds.
3) WordPress admin bar is also not working properly with this plugin.
This plugin contains 2 webpages.
First and the main page is loader.php
<?php
/*
Plugin Name: External Group Blogs
Plugin URI: http://wordpress.org/extend/plugins/external-group-blogs/
Description: Allow group creators to supply external blog RSS feeds that will attach future posts on blogs to a group.
*/
/* Only load the plugin functions if BuddyPress is loaded and initialized. */
function bp_groupblogs_init() {
require( dirname( __FILE__ ) . '/bp-groups-externalblogs.php' );
}
add_action( 'bp_init', 'bp_groupblogs_init' );
/* On activation register the cron to refresh external blog posts. */
function bp_groupblogs_activate() {
wp_schedule_event( time(), 'hourly', 'bp_groupblogs_cron' );
}
register_activation_hook( __FILE__, 'bp_groupblogs_activate' );
/* On deacativation, clear the cron. */
function bp_groupblogs_deactivate() {
wp_clear_scheduled_hook( 'bp_groupblogs_cron' );
/* Remove all external blog activity */
if ( function_exists( 'bp_activity_delete' ) )
bp_activity_delete( array( 'type' => 'exb' ) );
}
register_deactivation_hook( __FILE__, 'bp_groupblogs_deactivate' );
?>
And the 2nd file is bp-groups-externalblogs.php
<?php
/* Group blog extension using the BuddyPress group extension API */
if ( class_exists('BP_Group_Extension' ) ) {
class Group_External_Blogs extends BP_Group_Extension {
function __construct() {
global $bp;
$this->name = __( 'External Blogs', 'bp-groups-externalblogs' );
$this->slug = 'external-blog-feeds';
$this->create_step_position = 21;
$this->enable_nav_item = false;
}
function create_screen() {
global $bp;
if ( !bp_is_group_creation_step( $this->slug ) )
return false;
?>
<p><?php _e(
"Add RSS feeds of blogs you'd like to attach to this group in the box below.
Any future posts on these blogs will show up on the group page and be recorded
in activity streams.", 'bp-groups-externalblogs' ) ?>
</p>
<p class="desc"><?php _e( "Seperate URL's with commas.", 'bp-groups-externalblogs' ) ?></span>
<p>
<label for="blogfeeds"><?php _e( "Feed URL's:", 'bp-groups-externalblogs' ) ?></label>
<textarea name="blogfeeds" id="blogfeeds"><?php echo attribute_escape( implode( ', ', (array)groups_get_groupmeta( $bp->groups->current_group->id, 'blogfeeds' ) ) ) ?></textarea>
</p>
<?php
wp_nonce_field( 'groups_create_save_' . $this->slug );
}
function create_screen_save() {
global $bp;
check_admin_referer( 'groups_create_save_' . $this->slug );
$unfiltered_feeds = explode( ',', $_POST['blogfeeds'] );
foreach( (array) $unfiltered_feeds as $blog_feed ) {
if ( !empty( $blog_feed ) )
$blog_feeds[] = trim( $blog_feed );
}
groups_update_groupmeta( $bp->groups->current_group->id, 'blogfeeds', $blog_feeds );
groups_update_groupmeta( $bp->groups->current_group->id, 'bp_groupblogs_lastupdate', gmdate( "Y-m-d H:i:s" ) );
/* Fetch */
bp_groupblogs_fetch_group_feeds( $bp->groups->current_group->id );
}
function edit_screen() {
global $bp;
if ( !bp_is_group_admin_screen( $this->slug ) )
return false; ?>
<p class="desc"><?php _e( "Enter RSS feed URL's for blogs you would like to attach to this group. Any future posts on these blogs will show on the group activity stream. Seperate URL's with commas.", 'bp-groups-externalblogs' ) ?></span>
<p>
<label for="blogfeeds"><?php _e( "Feed URL's:", 'bp-groups-externalblogs' ) ?></label>
<textarea name="blogfeeds" id="blogfeeds"><?php echo attribute_escape( implode( ', ', (array)groups_get_groupmeta( $bp->groups->current_group->id, 'blogfeeds' ) ) ) ?></textarea>
</p>
<input type="submit" name="save" value="<?php _e( "Update Feed URL's", 'bp-groups-externalblogs' ) ?>" />
<?php
wp_nonce_field( 'groups_edit_save_' . $this->slug );
}
function edit_screen_save() {
global $bp;
if ( !isset( $_POST['save'] ) )
return false;
check_admin_referer( 'groups_edit_save_' . $this->slug );
$existing_feeds = (array)groups_get_groupmeta( $bp->groups->current_group->id, 'blogfeeds' );
$unfiltered_feeds = explode( ',', $_POST['blogfeeds'] );
foreach( (array) $unfiltered_feeds as $blog_feed ) {
if ( !empty( $blog_feed ) )
$blog_feeds[] = trim( $blog_feed );
}
/* Loop and find any feeds that have been removed, so we can delete activity stream items */
if ( !empty( $existing_feeds ) ) {
foreach( (array) $existing_feeds as $feed ) {
if ( !in_array( $feed, (array) $blog_feeds ) )
$removed[] = $feed;
}
}
if ( $removed ) {
/* Remove activity stream items for this feed */
include_once( ABSPATH . WPINC . '/rss.php' );
foreach( (array) $removed as $feed ) {
$rss = fetch_rss( trim( $feed ) );
if ( function_exists( 'bp_activity_delete' ) ) {
bp_activity_delete( array(
'item_id' => $bp->groups->current_group->id,
'secondary_item_id' => wp_hash( $rss->channel['link'] ),
'component' => $bp->groups->id,
'type' => 'exb'
) );
}
}
}
groups_update_groupmeta( $bp->groups->current_group->id, 'blogfeeds', $blog_feeds );
groups_update_groupmeta( $bp->groups->current_group->id, 'bp_groupblogs_lastupdate', gmdate( "Y-m-d H:i:s" ) );
/* Re-fetch */
bp_groupblogs_fetch_group_feeds( $bp->groups->current_group->id );
bp_core_add_message( __( 'External blog feeds updated successfully!', 'bp-groups-externalblogs' ) );
bp_core_redirect( bp_get_group_permalink( $bp->groups->current_group ) . '/admin/' . $this->slug );
}
/* We don't need display functions since the group activity stream handles it all. */
function display() {}
function widget_display() {}
}
bp_register_group_extension( 'Group_External_Blogs' );
function bp_groupblogs_fetch_group_feeds( $group_id = false ) {
global $bp;
include_once( ABSPATH . 'wp-includes/rss.php' );
if ( empty( $group_id ) )
$group_id = $bp->groups->current_group->id;
if ( $group_id == $bp->groups->current_group->id )
$group = $bp->groups->current_group;
else
$group = new BP_Groups_Group( $group_id );
if ( !$group )
return false;
$group_blogs = groups_get_groupmeta( $group_id, 'blogfeeds' );
$group_blogs = explode(";",$group_blogs[0]);
/* Set the visibility */
$hide_sitewide = ( 'public' != $group->status ) ? true : false;
foreach ( (array) $group_blogs as $feed_url ) {
$rss = fetch_feed( trim( $feed_url ) );
if (!is_wp_error($rss) ) {
foreach ( $rss->get_items(0,10) as $item ) {;
$key = $item->get_date( 'U' );
$items[$key]['title'] = $item->get_title();
$items[$key]['subtitle'] = $item->get_title();
//$items[$key]['author'] = $item->get_author()->get_name();
$items[$key]['blogname'] = $item->get_feed()->get_title();
$items[$key]['link'] = $item->get_permalink();
$items[$key]['blogurl'] = $item->get_feed()->get_link();
$items[$key]['description'] = $item->get_description();
$items[$key]['source'] = $item->get_source();
$items[$key]['copyright'] = $item->get_copyright();
}
}
}
if ( $items ) {
ksort($items);
$items = array_reverse($items, true);
} else {
return false;
}
/* Record found blog posts in activity streams */
foreach ( (array) $items as $post_date => $post ) {
//var_dump($post);
if (substr($post['blogname'],0,7) == "Twitter") {
$activity_action = sprintf( __( '%s from %s in the group %s', 'bp-groups-externalblogs' ), '<a class="feed-link" href="' . esc_attr( $post['link'] ) . '">Tweet</a>', '<a class="feed-author" href="' . esc_attr( $post['blogurl'] ) . '">' . attribute_escape( $post['blogname'] ) . '</a>', '' . attribute_escape( $group->name ) . '' );
} else {
$activity_action = sprintf( __( 'Blog: %s from %s in the group %s', 'bp-groups-externalblogs' ), '<a class="feed-link" href="' . esc_attr( $post['link'] ) . '">' . esc_attr( $post['title'] ) . '</a>', '<a class="feed-author" href="' . esc_attr( $post['blogurl'] ) . '">' . attribute_escape( $post['blogname'] ) . '</a>', '' . attribute_escape( $group->name ) . '' );
}
$activity_content = '<div>' . strip_tags( bp_create_excerpt( $post['description'], 175 ) ) . '</div>';
$activity_content = apply_filters( 'bp_groupblogs_activity_content', $activity_content, $post, $group );
/* Fetch an existing activity_id if one exists. */
if ( function_exists( 'bp_activity_get_activity_id' ) )
$id = bp_activity_get_activity_id( array( 'user_id' => false, 'action' => $activity_action, 'component' => $bp->groups->id, 'type' => 'exb', 'item_id' => $group_id, 'secondary_item_id' => wp_hash( $post['blogurl'] ) ) );
/* Record or update in activity streams. */
groups_record_activity( array(
'id' => $id,
'user_id' => false,
'action' => $activity_action,
'content' => $activity_content,
'primary_link' => $item->get_link(),
'type' => 'exb',
'item_id' => $group_id,
'secondary_item_id' => wp_hash( $post['blogurl'] ),
'recorded_time' => gmdate( "Y-m-d H:i:s", $post_date ),
'hide_sitewide' => $hide_sitewide
) );
}
return $items;
}
/* Add a filter option to the filter select box on group activity pages */
function bp_groupblogs_add_filter() { ?>
<option value="exb"><?php _e( 'External Blogs', 'bp-groups-externalblogs' ) ?></option><?php
}
add_action( 'bp_group_activity_filter_options', 'bp_groupblogs_add_filter' );
add_action( 'bp_activity_filter_options', 'bp_groupblogs_add_filter' );
/* Add a filter option groups avatar */
/* Fetch group twitter posts after 30 mins expires and someone hits the group page */
function bp_groupblogs_refetch() {
global $bp;
$last_refetch = groups_get_groupmeta( $bp->groups->current_group->id, 'bp_groupblogs_lastupdate' );
if ( strtotime( gmdate( "Y-m-d H:i:s" ) ) >= strtotime( '+30 minutes', strtotime( $last_refetch ) ) )
add_action( 'wp_footer', 'bp_groupblogs_refetch' );
/* Refetch the latest group twitter posts via AJAX so we don't stall a page load. */
function _bp_groupblogs_refetch() {
global $bp; ?>
<script type="text/javascript">
jQuery(document).ready( function() {
jQuery.post( ajaxurl, {
action: 'refetch_groupblogs',
'cookie': encodeURIComponent(document.cookie),
'group_id': <?php echo $bp->groups->current_group->id ?>
});
});
</script><?php
groups_update_groupmeta( $bp->groups->current_group->id, 'bp_groupblogs_lastupdate', gmdate( "Y-m-d H:i:s" ) );
}
}
add_action( 'groups_screen_group_home', 'bp_groupblogs_refetch' );
/* Refresh via an AJAX post for the group */
function bp_groupblogs_ajax_refresh() {
bp_groupblogs_fetch_group_feeds( $_POST['group_id'] );
}
add_action( 'wp_ajax_refetch_groupblogs', 'bp_groupblogs_ajax_refresh' );
function bp_groupblogs_cron_refresh() {
global $bp, $wpdb;
$group_ids = $wpdb->get_col( $wpdb->prepare( "SELECT group_id FROM " . $bp->groups->table_name_groupmeta . " WHERE meta_key = 'blogfeeds'" ) );
foreach( $group_ids as $group_id )
bp_groupblogs_fetch_group_feeds( $group_id );
}
add_action( 'bp_groupblogs_cron', 'bp_groupblogs_cron_refresh' );
}
// Add a filter option groups avatar
function bp_groupblogs_avatar_type($var) {
global $activities_template, $bp;
if ( $activities_template->activity->type == "exb" ) {
return 'group';
} else {
return $var;
}
}
add_action( 'bp_get_activity_avatar_object_groups', 'bp_groupblogs_avatar_type');
add_action( 'bp_get_activity_avatar_object_activity', 'bp_groupblogs_avatar_type');
function bp_groupblogs_avatar_id($var) {
global $activities_template, $bp;
if ( $activities_template->activity->type == "exb" ) {
return $activities_template->activity->item_id;
}
return $var;
}
add_action( 'bp_get_activity_avatar_item_id', 'bp_groupblogs_avatar_id');
?>
I have a suggestion for stopping data repeating in activity stream. Maybe use wp-cron api and a current date xml feeds fetching system once in a day. So it will not repeat the same feeds in a group activity stream. We need a criteria by which we can stop data repetition in the bp group activity stream. It is a part of my project. Is there another way of fetching feeds and saving it to the mysql table (in the group activity stream) and then show it as a latest group updates?
Actually IT IS fetching automatically.
I see the cron usage in a plugin. WordPress Cron fires only when any user opens your site. So no users (no pageviews) - no cron activity. On every pageview WP-Cron check whether the time to fire any function came or not.
Perhaps this plugin will help you a bit - display a RSS feed in a separate group tab.
I just set up a new input text option into my theme-options.php file, which is similar to the twenty eleven theme code.
Here are parts of my theme-options.php code in regards to the input, I'm looking for a way to get the input that users enter into the 'fact' text and show it on the index.php page:
function themename_theme_options_init() {
register_setting(
'themename_options', // Options group, see settings_fields() call in themename_theme_options_render_page()
'themename_theme_options', // Database option, see themename_get_theme_options()
'themename_theme_options_validate' // The sanitization callback, see themename_theme_options_validate()
);
// Register our settings field group
add_settings_section(
'general', // Unique identifier for the settings section
'', // Section title (we don't want one)
'__return_false', // Section callback (we don't want anything)
'theme_options' // Menu slug, used to uniquely identify the page; see themename_theme_options_add_page()
);
// Register our individual settings fields
add_settings_field( 'facts', __( 'Facts', 'themename' ), 'themename_settings_field_facts', 'theme_options', 'general' );
add_settings_field( 'link_color', __( 'Link Color', 'themename' ), 'themename_settings_field_link_color', 'theme_options', 'general' );
}
add_action( 'admin_init', 'themename_theme_options_init' );
Returns the default facts for Theme Name, based on color scheme:
function themename_get_default_facts( $color_scheme = null ) {
if ( null === $color_scheme ) {
$options = themename_get_theme_options();
$color_scheme = $options['color_scheme'];
}
$color_schemes = themename_color_schemes();
if ( ! isset( $color_schemes[ $color_scheme ] ) )
return false;
return $color_schemes[ $color_scheme ]['default_facts'];
}
Renders the Facts setting field.
function themename_settings_field_facts() {
$options = themename_get_theme_options();
?>
<input type="text" name="themename_theme_options[facts]" id="facts" value="<?php echo esc_attr( $options['facts'] ); ?>" />
<br />
<span><?php printf( __( 'Default facts: %s', 'themename' ), '<span id="default-facts">' . themename_get_default_facts ( $options['color_scheme'] ) . '</span>' ); ?></span>
<?php
}
Sanitize and validate form input:
function themename_theme_options_validate( $input ) {
$output = $defaults = themename_get_default_theme_options();
// Color scheme must be in our array of color scheme options
if ( isset( $input['color_scheme'] ) && array_key_exists( $input['color_scheme'], themename_color_schemes() ) )
$output['color_scheme'] = $input['color_scheme'];
// Facts must be characters.
if ( isset( $input['facts'] ) )
$output['facts'] = '' . ( ltrim( $input['facts'], '' ) );
// Our defaults for the link color may have changed, based on the color scheme.
$output['link_color'] = $defaults['link_color'] = themename_get_default_link_color( $output['color_scheme'] );
// Link color must be 3 or 6 hexadecimal characters
if ( isset( $input['link_color'] ) && preg_match( '/^#?([a-f0-9]{3}){1,2}$/i', $input['link_color'] ) )
$output['link_color'] = '#' . strtolower( ltrim( $input['link_color'], '#' ) );
return apply_filters( 'themename_theme_options_validate', $output, $input, $defaults );
}
Implements theme options into Theme Customizer:
function themename_customize_register( $wp_customize ) {
$wp_customize->get_setting( 'blogname' )->transport = 'postMessage';
$wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage';
$options = themename_get_theme_options();
$defaults = themename_get_default_theme_options();
$wp_customize->add_setting( 'themename_theme_options[facts]', array(
'default' => themename_get_default_facts( $options['color_scheme'] ),
'type' => 'option',
'sanitize_callback' => 'sanitize_text_field',
'capability' => 'edit_theme_options',
) );
}
add_action( 'customize_register', 'themename_customize_register' );
Thank you to anyone that can help :)
Thanks! I got it working :D
----------
<?php
/**
* Theme Options
*
* #package WordPress
*
*/
/* Write the name and the variable_name in which you want to store the data using theme options in the array $options_array */
$options_array = array(
'Facebook URL'=>'facebook_url',
);
function my_theme_options_init() {
// If we have no options in the database, let's add them now.
if ( false === my_theme_options() )
add_option( 'my_theme_options', my_default_theme_options() );
register_setting(
'my_options', // Options group, see settings_fields() call in theme_options_render_page()
'my_theme_options' // Database option, see my_theme_options()
);
global $options_array;
foreach ($options_array as $key=>$option ){
register_setting( 'my_options', $option);
}
}
add_action( 'admin_init', 'my_theme_options_init' );
function my_theme_options_add_page() {
$theme_page = add_theme_page(
'myers themeing', // Name of page
'myers themeing', // Label in menu
'edit_theme_options', // Capability required
'my_options', // Menu slug, used to uniquely identify the page
'my_theme_options_render_page' // Function that renders the options page
);
if ( ! $theme_page )
return;
}
add_action( 'admin_menu', 'my_theme_options_add_page' );
function my_default_schemes() {
$default_array = array('value' => 'Default_theme',
'label' => __( 'Default_theme', 'my' ),
'thumbnail' => get_template_directory_uri() . '/inc/images/my.png'
);
global $options_array;
foreach ($options_array as $key=>$option ){
$default_array[$option] =' ';
}
$default_scheme_options = array(
'Default_theme' => $default_array,
);
return apply_filters( 'my_default_schemes', $default_scheme_options );
}
function my_default_theme_options() {
$default_theme_options = array( 'default_scheme' => 'Default_theme' );
global $options_array;
foreach ($options_array as $key=>$option ){
$default_theme_options[$option] = my_default( $option,'Default_theme' );
}
return apply_filters( 'my_default_theme_options', $default_theme_options );
}
function my_default( $option ,$default_scheme = null ) {
if ( null === $default_scheme ) {
$options = my_theme_options();
$default_scheme = $options['default_scheme'];
}
$default_schemes = my_default_schemes();
if ( ! isset( $default_schemes[ $default_scheme ] ) )
return false;
return $default_schemes[ $default_scheme ][$option];
}
function my_theme_options() {
return get_option( 'my_theme_options', my_default_theme_options() );
}
function my_theme_options_render_page() {
?>
<div class="wrap">
<?php screen_icon(); ?>
<h2><?php printf( __( '%s Theme Options', 'my' ), get_current_theme() ); ?></h2>
<?php settings_errors(); ?>
<hr>
<div id="theme_option_main">
<h2>myers themeing</h2>
<form method="post" enctype="multipart/form-data" action="options.php">
<?php
settings_fields( 'my_options' );
$options = my_theme_options();
$default_options = my_default_theme_options();
global $options_array;
foreach ($options_array as $key=>$option ){
do_settings_sections($option);
}
?>
<table class="form-table">
<tr>
<th scope="row"><?php _e( "(Use ' http:// ' for Hyperlinks)", 'my' ); ?></th>
<td>
<fieldset>
</fieldset>
</td>
</tr>
<?php
foreach ($options_array as $key=>$option ){
?>
<tr>
<th scope="row"><?php _e( $key, 'my' ); ?></th>
<td>
<fieldset>
<legend class="screen-reader-text"><span><?php _e( $key, 'my' ); ?></span></legend>
<input type="text" name="<?php echo $option ?>" id="<?php echo $option ?>" class="large-text" value="<?php echo get_option($option); ?>"></input>
</fieldset>
</td>
</tr>
<?php } ?>
</table>
<?php submit_button(); ?>
</form>
</div>
</div>
<?php
}
?>
copy the code and create a new theme options file. Add the name and the variable_name in the options array in the file and you are good to go.
Don't forget to link this file in your functions.php
To link it just add the following code in your functions.php
require( dirname( __FILE__ ) . '/inc/your_file_name.php' );