How to get input text from theme options on wordpress? - php

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' );

Related

Adding products from specific Ids in WooCommerce product custom tab

I am using the code generated based on Add a custom multi-select field to admin product options settings in Woocommerce
// Display a multiselect field in "Linked Products" section
add_action( 'woocommerce_product_options_related', 'display_handles_product_field' );
function display_handles_product_field() {
global $product_object, $post;
?>
<p class="form-field">
<label for="handles_product"><?php _e( 'Handles Product', 'woocommerce' ); ?></label>
<select class="wc-product-search" multiple="multiple" id="handles_product_ids" name="_handles_product_ids[]" data-placeholder="<?php esc_attr_e( 'Search for a product…', 'woocommerce' ); ?>" data-action="woocommerce_json_search_products_and_variations" data-exclude="<?php echo intval( $post->ID ); ?>">
<?php
$product_ids = $product_object->get_meta( '_handles_product_ids' );
foreach ( $product_ids as $product_id ) {
$product = wc_get_product( $product_id );
if ( is_object( $product ) ) {
echo '<option value="' . esc_attr( $product_id ) . '"' . selected( true, true, false ) . '>' . wp_kses_post( $product->get_formatted_name() ) . '</option>';
}
}
?>
</select>
</p>
<?php
}
// Save the values to the product
add_action( 'woocommerce_admin_process_product_object', 'save_handles_product_field_value', 10, 1 );
function save_handles_product_field_value( $product ){
$data = isset( $_POST['_handles_product_ids'] ) ? array_map( 'intval', (array) $_POST['_handles_product_ids'] ) : array();
$product->update_meta_data( '_handles_product_ids', $data );
}
This code adds a custom search box and adds related products in the admin area when creating or editing a product.
I also created a new tab on the product page to show the added products.
/* New Handles Product Tab */
add_filter( 'woocommerce_product_tabs', 'new_handles_product_tab' );
function new_handles_product_tab( $tabs ) {
/* Add new tab */
$tabs['new_handles_product_tab'] = array(
'title' => __( 'Handles Product', 'woocommerce' ),
'priority' => 50,
'callback' => 'new_handles_product_tab_content'
);
return $tabs;
}
/* Display content in new tab */
function new_handles_product_tab_content() {
// Content
}
Tell me how to add these products to the new tab correctly? And is my code correct?
I will be glad for your help!
Using [products] shortcode with ids argument, the function displaying the product handles in a custom product tab will be:
function new_handles_product_tab_content() {
global $product;
$product_ids = $product->get_meta( '_handles_product_ids' ); // Get handles
if( ! empty($product_ids) )
$product_ids = implode(',', $product_ids);
echo do_shortcode( "[products ids='$product_ids']" ); // Using [products] shortcode for display.
}
Untested it should work.

How to convert the WordPress meta box Page Attributes->Page Template dropdown to radio buttons?

I would like to be able to change the Page Attribute "Templates" dropdown to radio buttons, to allow me to have corresponding thumbnails next to them.
It looks like this question was already asked here - Is it possible to make WordPress page attribute meta box select option display as images? - however no code was ever supplied and looking at the comments it appears that the user answered their own question?
I have already removed and replaced the Page Attributes meta box on functions.php, as per below:
add_action( 'add_meta_boxes', 'wpse44966_add_meta_box' );
function wpse44966_add_meta_box( $post_type ){
remove_meta_box(
'pageparentdiv',
'page',
'side');
add_meta_box(
'wpse44966-meta-box',
'page' == $post_type ? __('Page Style Templates') : __('Attributes'),
'wpse44966_meta_box_cb',
'page',
'side',
'low');
}
I am then able to call back the "Templates" dropdown in my own meta box - I have also included the page_template_dropdown function (renamed 'page_template_dropdown_show_it').
function page_template_dropdown_show_it( $default = '', $post_type = 'page' ) {
$templates = get_page_templates( null, $post_type );
ksort( $templates );
foreach ( array_keys( $templates ) as $template ) {
$selected = selected( $default, $templates[ $template ], false );
echo "\n\t<option value='" . esc_attr( $templates[ $template ] ) . "' $selected>" . esc_html( $template ) . '</option>';
}
}
function wpse44966_meta_box_cb( $post ){
echo 'Please select from the below';
if ( count( get_page_templates( $post ) ) > 0 && get_option( 'page_for_posts' ) != $post->ID ) :
$template = ! empty( $post->page_template ) ? $post->page_template : false; ?>
<p class="post-attributes-label-wrapper"><label class="post-attributes-label" for="page_template"><?php _e( 'Template' ); ?></label><?php do_action( 'page_attributes_meta_box_template', $template, $post ); ?></p>
<select name="page_template" id="page_template">
<?php $default_title = apply_filters( 'default_page_template_title', __( 'Default Template' ), 'meta-box' ); ?>
<option value="default"><?php echo esc_html( $default_title ); ?></option>
<?php page_template_dropdown_show_it( $template, $post->post_type ); ?>
</select>
<?php endif;
}
However, when I then amend both page_template_dropdown_show_it and wpse44966_meta_box_cb to show radio buttons, the changes are applied visually but nothing happens when you select them?
function page_template_dropdown_show_it( $default = '', $post_type = 'page' ) {
$templates = get_page_templates( null, $post_type );
ksort( $templates );
foreach ( array_keys( $templates ) as $template ) {
$checked = checked( $default, $templates[ $template ], false );
echo "\n\t<input type='radio' name='page_template' value='" . esc_attr( $templates[ $template ] ) . "' $checked>" . esc_html( $template );
}
}
function wpse44966_meta_box_cb( $post ){
echo 'Please select from the below';
if ( count( get_page_templates( $post ) ) > 0 && get_option( 'page_for_posts' ) != $post->ID ) :
$template = ! empty( $post->page_template ) ? $post->page_template : false; ?>
<p class="post-attributes-label-wrapper"><label class="post-attributes-label" for="page_template"><?php _e( 'Template' ); ?></label><?php do_action( 'page_attributes_meta_box_template', $template, $post ); ?></p>
<?php $default_title = apply_filters( 'default_page_template_title', __( 'Default Template' ), 'meta-box' ); ?>
<input type='radio' name='page_template' value="default"><?php echo esc_html( $default_title ); ?>
<?php page_template_dropdown_show_it( $template, $post->post_type ); ?>
<?php endif;
}
It's obviously not as simple as a straight swap-out (as it isn't working), but the only thing that I can see that is missing is now there is nothing carrying the id="page_template", whereas before it was included in the below:
<select name="page_template" id="page_template">
So, it appears that I was correct that the issue was that the id "page_template" was no longer being passed.
To solve this, all I have done is applied some Javascript (using the admin_enqueue_scripts function) which adds the id "page_template" to the radio button that has been selected.

How to use variation and add-to-cart button outside woocommerce loop

I'm using woocommerce for my website, but as I only have one main product and two accessories (related products), I don't need a classic shop page, neither single-product pages for each of my product. My main product has a color variation.
I want to have an add-to-cart button, with the color variation dropdown and the quantity field in one of my regular post page. Exactly like on a single-product page, but embedded in my own page, and without the parts of the single-product page I don't need (description, ...).
I finally decided to achieve this using two custom shortcodes I created: [my_vc_product_price id="xxx"] and [my_vc_add2cart_variable_product id="xxx"]. So I can put them where I want.
But my problem is that the behavior of the dropdown menu + variation availability + add-to-cart button is not the same that this elements have in the single-product page:
- the availability of he variation doesn't show up when I choose the color in the dropdown menu;
- the add-to-cart button is not disable when no color is chosen in the dropdown menu (it should be disable and active only when a color is chosen).
Displaying the price was easy, using some code found on internet:
/**
* Add shortcode to allow to display product price in a page
*/
function my_vc_display_product_price( $args ) {
$product_id = $args['id'];
$product = wc_get_product( $product_id );
echo '<p class="price">' . $product->get_price_html() . '</p>';
}
add_shortcode( 'my_vc_product_price', 'my_vc_display_product_price');
To get the same graphical result, I just had to add some CSS classes on the row: "woocommerce" and "product".
The code to display the dropdown menu + the quantity and the add-to-cart button is almost the same than in the variable.php file found in plugins/woocommerce/templates/single-product/add-to-cart/. The only things really change is that you need to get the "variation attributes" of the product, and not the attributes.
$attributes = $product->get_variation_attributes();
$attribute_keys = array_keys( $attributes );
So the full function code is:
/**
* Add shortcode to allow to display an add to cart button with dropdown menu for variation attributes
*/
function my_vc_add_to_cart_button_variable_product( $args ) {
global $product;
$product_id = $args['id'];
$product = wc_get_product( $product_id );
if( $product->is_type( 'variable' )) {
$attributes = $product->get_variation_attributes();
$attribute_keys = array_keys( $attributes );
$available_variations = array( $product->get_available_variations() );
do_action( 'woocommerce_before_add_to_cart_form' ); ?>
<form class="variations_form cart" method="post" enctype='multipart/form-data' data-product_id="<?php echo absint( $product->get_id() ); ?>" data-product_variations="<?php echo htmlspecialchars( wp_json_encode( $available_variations ) ) ?>">
<?php do_action( 'woocommerce_before_variations_form' ); ?>
<?php if ( empty( $available_variations ) && false !== $available_variations ) : ?>
<p class="stock out-of-stock"><?php _e( 'This product is currently out of stock and unavailable.', 'woocommerce' ); ?></p>
<?php else : ?>
<table class="variations" cellspacing="0">
<tbody>
<?php foreach ( $attributes as $attribute_name => $options ) : ?>
<tr>
<td class="value">
<?php
$selected = isset( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ? wc_clean( stripslashes( urldecode( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ) ) : $product->get_variation_default_attribute( $attribute_name );
wc_dropdown_variation_attribute_options( array( 'options' => $options, 'attribute' => $attribute_name, 'product' => $product, 'selected' => $selected ) );
?>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
<?php do_action( 'woocommerce_before_add_to_cart_button' ); ?>
<div class="single_variation_wrap">
<?php
/**
* woocommerce_before_single_variation Hook.
*/
do_action( 'woocommerce_before_single_variation' );
/**
* woocommerce_single_variation hook. Used to output the cart button and placeholder for variation data.
* #since 2.4.0
* #hooked woocommerce_single_variation - 10 Empty div for variation data.
* #hooked woocommerce_single_variation_add_to_cart_button - 20 Qty and cart button.
*/
do_action( 'woocommerce_single_variation' );
?>
<script type="text/template" id="tmpl-variation-template">
<div class="woocommerce-variation-description">{{{ data.variation.variation_description }}}</div>
<div class="woocommerce-variation-price">{{{ data.variation.price_html }}}</div>
<div class="woocommerce-variation-availability">{{{ data.variation.availability_html }}}</div>
</script>
<script type="text/template" id="tmpl-unavailable-variation-template">
<p><?php _e( 'Sorry, this product is unavailable. Please choose a different combination.', 'woocommerce' ); ?></p>
</script>
<?php
/**
* woocommerce_after_single_variation Hook.
*/
do_action( 'woocommerce_after_single_variation' );
?>
</div>
<?php do_action( 'woocommerce_after_add_to_cart_button' ); ?>
<?php endif; ?>
<?php do_action( 'woocommerce_after_variations_form' ); ?>
</form>
<?php
do_action( 'woocommerce_after_add_to_cart_form' );
}
}
add_shortcode( 'my_vc_add2cart_variable_product', 'my_vc_add_to_cart_button_variable_product');
Any idea what is going wrong? I don't understand, if the code is the same, why it didn't execute the same. Is there something missing because this code is outside woocommerce pages?
try using following code
function add_to_cart_form_shortcode( $atts ) {
if ( empty( $atts ) ) {
return '';
}
if ( ! isset( $atts['id'] ) && ! isset( $atts['sku'] ) ) {
return '';
}
$args = array(
'posts_per_page' => 1,
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'no_found_rows' => 1,
);
if ( isset( $atts['sku'] ) ) {
$args['meta_query'][] = array(
'key' => '_sku',
'value' => sanitize_text_field( $atts['sku'] ),
'compare' => '=',
);
$args['post_type'] = array( 'product', 'product_variation' );
}
if ( isset( $atts['id'] ) ) {
$args['p'] = absint( $atts['id'] );
}
$single_product = new WP_Query( $args );
$preselected_id = '0';
if ( isset( $atts['sku'] ) && $single_product->have_posts() && 'product_variation' === $single_product->post->post_type ) {
$variation = new WC_Product_Variation( $single_product->post->ID );
$attributes = $variation->get_attributes();
$preselected_id = $single_product->post->ID;
$args = array(
'posts_per_page' => 1,
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'no_found_rows' => 1,
'p' => $single_product->post->post_parent,
);
$single_product = new WP_Query( $args );
?>
<script type="text/javascript">
jQuery( document ).ready( function( $ ) {
var $variations_form = $( '[data-product-page-preselected-id="<?php echo esc_attr( $preselected_id ); ?>"]' ).find( 'form.variations_form' );
<?php foreach ( $attributes as $attr => $value ) { ?>
$variations_form.find( 'select[name="<?php echo esc_attr( $attr ); ?>"]' ).val( '<?php echo esc_js( $value ); ?>' );
<?php } ?>
});
</script>
<?php
}
$single_product->is_single = true;
ob_start();
global $wp_query;
$previous_wp_query = $wp_query;
$wp_query = $single_product;
wp_enqueue_script( 'wc-single-product' );
while ( $single_product->have_posts() ) {
$single_product->the_post()
?>
<div class="single-product" data-product-page-preselected-id="<?php echo esc_attr( $preselected_id ); ?>">
<?php woocommerce_template_single_add_to_cart(); ?>
</div>
<?php
}
$wp_query = $previous_wp_query;
wp_reset_postdata();
return '<div class="woocommerce">' . ob_get_clean() . '</div>';
}
add_shortcode( 'add_to_cart_form', 'add_to_cart_form_shortcode' );
/*Example Usage [add_to_cart_form id=147]*/
That's just perfect! Many thanks.
Now the hardest to come: I need to understand your code and compare it with mine ;-)

VIM syntax highlighting 'buggy'?

I switched from intelliJ to VIM a few days ago and I have a few problems with my syntax highlighting. I'm mainly working with php and html and in some files some of the ; are marked with a red background (maybe meaning there is an error in my syntax?). This most likely happens when the ; is followed by a comment //. I'm pretty sure there are no errors...
Also a few files do not provide php syntax highlight at all after a blockcomment /**/ until the php tag ?> gets closed.
Any idea what im missing? Also I'd appreciate suggestions on alternatives for syntax highlighting. It's hard to find useful stuff for webdev since VIM isn't that popular in that sector I guess.
Here my current vim settings:
https://github.com/raQai/.vim
I'd appreciate your help
Edit:
Here is the code thats causing the problems:
<?php namespace KF\LINKS;
defined ( 'ABSPATH' ) or die ( 'nope!' );
/**
* Plugin Name: KF Attachment Links
* Description: Adding attatchemts to post, pages and teams (Kong Foos Team Manager)
* Version: 1.0.0
* Author: Patrick Bogdan
* Text Domain: kfl
* License: GPL2
*
* Copyright 2015 Patrick Bogdan
* TODO: Settings for post_types with checkboxes
*/
new KFLinksMetaBox();
class KFLinksMetaBox {
const kfl_key = 'kf-links-information';
function __construct() {
if (is_admin ()) {
add_action ( 'admin_enqueue_scripts', wp_enqueue_style ( 'kfl-admin-style', plugins_url( 'includes/css/admin-styles.css', plugin_basename( __FILE__ ) ) ) );
add_action ( 'admin_enqueue_scripts', wp_enqueue_script ( 'kfl-admin-js', plugins_url( 'includes/js/kfl-admin-scripts.js', plugin_basename( __FILE__ ) ) ) );
add_action ( 'add_meta_boxes', array( &$this, 'kf_links_meta_box_add' ) );
add_action ( 'save_post', array( &$this, 'kf_links_meta_box_save' ) );
}
register_deactivation_hook( __FILE__, array( &$this, 'kf_links_uninstall' ) );
add_filter( 'the_content', array( $this, 'kf_links_add_to_posts' ) );
}
function kf_links_uninstall() {
delete_post_meta_by_key( self::kfl_key );
}
function kf_links_add_to_posts( $content ) {
$links = $this->kf_links_explode( get_post_meta( get_the_ID(), self::kfl_key, true ) );
if ( $links['is_active'] == '1' && count($links['items']) > 0 ) {
$links_html = '';
if ( !empty($links['title']) ) {
$links_html .= '<strong>' . $links['title'] . '</strong>';
}
foreach ( $links['items'] as $link ) {
if ( !empty( $link['name'] ) && !empty( $link['url'] ) ) {
$links_html .= '<br />» ' . $link['name'] . '';
}
}
if ( !empty( $links_html ) ) {
$content .= '<p class="attachment-links">' . $links_html . '</p>';
}
}
return $content;
}
function kf_links_meta_box_add() {
$screens = array( 'post', 'page', 'teams' );
foreach( $screens as $screen)
{
add_meta_box (
'kf_links_meta_box', // id
'Linksammlung', // title
array( &$this, 'kf_links_meta_box_display' ), // callback
$screen, // post_type
'normal', // context
'high' // priority
);
}
}
function kf_links_meta_box_display( $post ) {
wp_nonce_field( 'kf_links_meta_box', 'kf_links_meta_box_nonce' );
$this->kf_links_meta_box_display_html( $post );
}
function kf_links_meta_box_display_html( $post )
{
$post_string = get_post_meta( $post->ID, self::kfl_key, true );
$links = $this->kf_links_explode( $post_string );
?>
<div class="kf-meta-box-checkbox">
<input onClick="kfl_checkboxDivDisplay( this.id, 'kf-links' ); kfl_creaetLinksString();" <?php if ( $links['is_active'] ) echo 'checked '; ?>type="checkbox" id="kf-links-checkbox" value="1" />
<label id="kf-links-checkbox-label" for="kf-links-checkbox">Linksammlung aktivieren</label>
</div>
<div id="kf-links" <?php if ( !$links['is_active'] ) echo 'style="display:none" '; ?>>
<div class="kf-meta-box-full">
<label for="kf-links-title">Titel der Linksammlung</label>
<input onChange="kfl_creaetLinksString()" id="kf-links-title" value="<?php echo $links['title']; ?>" placeholder="Titel der Linksammlung" />
</div>
<div class="kf-links-header">
<label>Name</label>
<label>URL</label>
</div>
<div id="kf-links-items">
<?php
foreach ( $links['items'] as $ID => $arr ) {
$this->kf_links_item_display_html( $ID, $arr, $links['is_active'] );
}
if ( count( $links['items'] ) < 1 ) {
$this->kf_links_item_display_html( 0, array( 'name' => '', 'url' => '' ), false );
}
?>
</div>
<h4>+ Weiteren Link hinzufügen</h4>
<input type="hidden" id="kf-links-counter" value="<?php echo ( ( count($links['items']) < 1 ) ? 1 : count($links['items']) ); ?>" />
<input type="hidden" name="<?php echo self::kfl_key; ?>" id="<?php echo self::kfl_key; ?>" value="<?php echo $post_string; ?>" />
</div>
<?php
}
function kf_links_item_display_html( $ID, $arr, $is_active )
{
?>
<div id="kf-links-item[<?php echo $ID; ?>]" class="kf-links-item">
<input onChange="kfl_creaetLinksString();" value="<?php echo $arr['name']; ?>" <?php if ( $is_active ) echo 'required '; ?>placeholder="Name" />
<input onChange="kfl_creaetLinksString();" value="<?php echo $arr['url']; ?>" <?php if ( $is_active ) echo 'required '; ?>placeholder="http://..." />
<input onClick="kfl_deleteLink( 'kf-links-item[<?php echo $ID; ?>]' ); kfl_creaetLinksString();" value="&cross;" type="button" class="button button-small button-primary" />
</div>
<?php
}
function kf_links_meta_box_save($post_id)
{
if ( !isset( $_POST['kf_links_meta_box_nonce'] ) || ! wp_verify_nonce( $_POST['kf_links_meta_box_nonce'], 'kf_links_meta_box' )) {
return $post_id;
}
$post_type = get_post_type_object( $_POST['post_type'] );
if ( !current_user_can( $post_type->cap->edit_post, $post_id ) ) {
return;
}
$new_meta_value = ( isset( $_POST[self::kfl_key] ) ? $_POST[self::kfl_key] : '');
update_post_meta( $post_id, self::kfl_key, $new_meta_value );
}
function kf_links_explode( $string )
{
if ( empty($string) || !is_string($string) ) {
$links['is_active'] = 0;
return $links;
}
$explode = explode( ';$;', $string );
$links['is_active'] = ( isset( $explode[0] ) ? $explode[0] : 0 );
$links['title'] = ( isset( $explode[1] ) ? $explode[1] : '' );
$links['items'] = array();
for ( $i = 2; $i < count( $explode ); $i++ ) {
$explode2 = explode( ';?;', $explode[$i] );
$link = array(
'name' => $explode2[0],
'url' => $explode2[1]
);
$links['items'][] = $link;
}
return $links;
}
}
And here some screenshots:
https://www.dropbox.com/sh/jj3gluc7ok001hu/AABq_hRiKcbbDo1E0rKpP2Jxa?dl=0
Try :syntax sync fromstart.
If that works, add autocmd BufEnter * :syntax sync fromstart to your .vimrc
Explanation: if the syntax highlighter does not process every line of code from the beginning, it may not receive a critical piece of information to understand what type of code it's processing. E.g., if you're in an HTML file and deep within a script tag, the syntax highlighter may not look back far enough to see the script tag and therefore processes your JS code as HTML.

Using style.php and style.css on wordpress together

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;
}
}

Categories