Problem with foreach array on select option on woocmmerce function class - php

I create a function to add different shiping prices foreach user, all works fine for only one user (the first on the list), but i can't get to make the select options foreach user, it only shows 1 option with all the user in it.
the problem is integrate the foreach in here: 'test' => array. It creates the html elemnt but only 1 and not 1 foreach user
my code:
class WC_Shipping_click extends WC_Shipping_Method {
public function __construct( $instance_id = 0 ) {
$args = array(
'role' => '',
'orderby' => 'user_nicename',
'order' => 'ASC'
);
$users = get_users( $args );
foreach ( $users as $user ){
$userinfo .= '['.$user->precio.','.$user->first_name.'] ';
}
$this->id = 'click_method';
$this->instance_id = absint( $instance_id );
$this->method_title = __( 'Click Shipping Method' );
$this->method_description = __( 'Click Shipping' );
$this->supports = array(
'shipping-zones',
'instance-settings',
'instance-settings-modal',
);
$this->instance_form_fields = array(
'enabled' => array(
'title' => __( 'Enable/Disable' ),
'type' => 'checkbox',
'label' => __( 'Enable this shipping method' ),
'default' => 'yes',
),
'test' => array(
'title' => __( 'Prueba de array' ),
'description' => $user->first_name,
'type' => 'select',
'options' => array( ''.$userinfo.'' => ''.$userinfo'',),
'label' => __( 'Some field' ),
'required' => true,
)
)
);
$this->enabled = $this->get_option( 'enabled' );
$this->prueba = $this->get_option( 'prueba' );
add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
}
/**
* #param array $package (default: array())
*/
public function calculate_shipping( $package = array() ) {
$this->add_rate( array(
'id' => $this->id . $this->instance_id,
'label' => $this->title,
'cost' => $this->test,
) );
}
}

This is the scope of your foreach()
foreach ( $users as $user ){
$userinfo .= '['.$user->precio.','.$user->first_name.'] ';
}
Nothing that is below will fall into this foreach() loop.

Related

Add a custom WooCommerce settings page, including page sections

I'm trying to add a custom settings tab to the WooCommerce settings screen. Basically I want to achieve a similar thing to the Products settings tab, with the subsections/subtabs:
I haven't been able to find any decent documentation on how to do this but I've been able to add a custom tab using this snippet:
class WC_Settings_Tab_Demo {
public static function init() {
add_filter( 'woocommerce_settings_tabs_array', __CLASS__ . '::add_settings_tab', 50 );
}
public static function add_settings_tab( $settings_tabs ) {
$settings_tabs['test'] = __( 'Settings Demo Tab', 'woocommerce-settings-tab-demo' );
return $settings_tabs;
}
}
WC_Settings_Tab_Demo::init();
Based on what I've dug up from various threads/tutorials, I've been trying to add the sections/subtabs to the new settings tab something like this:
// creating a new sub tab in API settings
add_filter( 'woocommerce_get_sections_test','add_subtab' );
function add_subtab( $sections ) {
$sections['custom_settings'] = __( 'Custom Settings', 'woocommerce-custom-settings-tab' );
$sections['more_settings'] = __( 'More Settings', 'woocommerce-custom-settings-tab' );
return $sections;
}
// adding settings (HTML Form)
add_filter( 'woocommerce_get_settings_test', 'add_subtab_settings', 10, 2 );
function add_subtab_settings( $settings, $current_section ) {
// $current_section = (isset($_GET['section']) && !empty($_GET['section']))? $_GET['section']:'';
if ( $current_section == 'custom_settings' ) {
$custom_settings = array();
$custom_settings[] = array( 'name' => __( 'Custom Settings', 'text-domain' ),
'type' => 'title',
'desc' => __( 'The following options are used to ...', 'text-domain' ),
'id' => 'custom_settings'
);
$custom_settings[] = array(
'name' => __( 'Field 1', 'text-domain' ),
'id' => 'field_one',
'type' => 'text',
'default' => get_option('field_one'),
);
$custom_settings[] = array( 'type' => 'sectionend', 'id' => 'test-options' );
return $custom_settings;
} else {
// If not, return the standard settings
return $settings;
}
}
I've been able to add new subsections to the Products tab using similar code to the above, but it isn't working for my new custom tab. Where am I going wrong here?
1) To add a setting tab with sections, you can firstly use the woocommerce_settings_tabs_array filter hook:
// Add the tab to the tabs array
function filter_woocommerce_settings_tabs_array( $settings_tabs ) {
$settings_tabs['my-custom-tab'] = __( 'My custom tab', 'woocommerce' );
return $settings_tabs;
}
add_filter( 'woocommerce_settings_tabs_array', 'filter_woocommerce_settings_tabs_array', 99 );
2) To add new sections to the page, you can use the woocommerce_sections_{$current_tab} composite hook where {$current_tab} need to be replaced by the key slug that is set in the first function:
// Add new sections to the page
function action_woocommerce_sections_my_custom_tab() {
global $current_section;
$tab_id = 'my-custom-tab';
// Must contain more than one section to display the links
// Make first element's key empty ('')
$sections = array(
'' => __( 'Overview', 'woocommerce' ),
'my-section-1' => __( 'My section 1', 'woocommerce' ),
'my-section-2' => __( 'My section 2', 'woocommerce' )
);
echo '<ul class="subsubsub">';
$array_keys = array_keys( $sections );
foreach ( $sections as $id => $label ) {
echo '<li>' . $label . ' ' . ( end( $array_keys ) == $id ? '' : '|' ) . ' </li>';
}
echo '</ul><br class="clear" />';
}
add_action( 'woocommerce_sections_my-custom-tab', 'action_woocommerce_sections_my_custom_tab', 10 );
3) For adding the settings, as well as for processing/saving, we will use a custom function, which we will then call:
// Settings function
function get_custom_settings() {
global $current_section;
$settings = array();
if ( $current_section == 'my-section-1' ) {
// My section 1
$settings = array(
// Title
array(
'title' => __( 'Your title 1', 'woocommerce' ),
'type' => 'title',
'id' => 'custom_settings_1'
),
// Text
array(
'title' => __( 'Your title 1.1', 'text-domain' ),
'type' => 'text',
'desc' => __( 'Your description 1.1', 'woocommerce' ),
'desc_tip' => true,
'id' => 'custom_settings_1_text',
'css' => 'min-width:300px;'
),
// Select
array(
'title' => __( 'Your title 1.2', 'woocommerce' ),
'desc' => __( 'Your description 1.2', 'woocommerce' ),
'id' => 'custom_settings_1_select',
'class' => 'wc-enhanced-select',
'css' => 'min-width:300px;',
'default' => 'aa',
'type' => 'select',
'options' => array(
'aa' => __( 'aa', 'woocommerce' ),
'bb' => __( 'bb', 'woocommerce' ),
'cc' => __( 'cc', 'woocommerce' ),
'dd' => __( 'dd', 'woocommerce' ),
),
'desc_tip' => true,
),
// Section end
array(
'type' => 'sectionend',
'id' => 'custom_settings_1'
),
);
} elseif ( $current_section == 'my-section-2' ) {
// My section 2
$settings = array(
// Title
array(
'title' => __( 'Your title 2', 'woocommerce' ),
'type' => 'title',
'id' => 'custom_settings_2'
),
// Text
array(
'title' => __( 'Your title 2.2', 'text-domain' ),
'type' => 'text',
'desc' => __( 'Your description 2.1', 'woocommerce' ),
'desc_tip' => true,
'id' => 'custom_settings_2_text',
'css' => 'min-width:300px;'
),
// Section end
array(
'type' => 'sectionend',
'id' => 'custom_settings_2'
),
);
} else {
// Overview
$settings = array(
// Title
array(
'title' => __( 'Overview', 'woocommerce' ),
'type' => 'title',
'id' => 'custom_settings_overview'
),
// Section end
array(
'type' => 'sectionend',
'id' => 'custom_settings_overview'
),
);
}
return $settings;
}
3.1) Add settings, via the woocommerce_settings_{$current_tab} composite hook:
// Add settings
function action_woocommerce_settings_my_custom_tab() {
// Call settings function
$settings = get_custom_settings();
WC_Admin_Settings::output_fields( $settings );
}
add_action( 'woocommerce_settings_my-custom-tab', 'action_woocommerce_settings_my_custom_tab', 10 );
3.2) Process/save the settings, via the woocommerce_settings_save_{$current_tab} composite hook:
// Process/save the settings
function action_woocommerce_settings_save_my_custom_tab() {
global $current_section;
$tab_id = 'my-custom-tab';
// Call settings function
$settings = get_custom_settings();
WC_Admin_Settings::save_fields( $settings );
if ( $current_section ) {
do_action( 'woocommerce_update_options_' . $tab_id . '_' . $current_section );
}
}
add_action( 'woocommerce_settings_save_my-custom-tab', 'action_woocommerce_settings_save_my_custom_tab', 10 );
Result:
Based on:
Implement a custom WooCommerce settings page, including page sections
woocommerce/includes/admin/settings/

Duplicate admin menu settings in wordpress

I am sorry if the title isn't correct, but I have no idea about those coding stuff I don't know how to explain it.
I am using WordPress and my theme has a build-in mega menu.
The problem is that the mega menu settings in admin panel appear twice while inside the file just one.
Example in screenshot below:
Here is the settings file:
<?php if ( ! defined( 'ABSPATH' ) ) { die; }
if(!class_exists('Veera_MegaMenu_Init')){
class Veera_MegaMenu_Init{
protected $fields = array();
protected $default_metakey = '';
public function __construct() {
$query_args = array(
'post_type' => 'la_block',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => 20
);
$this->default_metakey = '_mm_meta';
$this->fields = array(
'icon' => array(
'id' => 'icon',
'type' => 'icon',
'title' => esc_html__('Custom Icon','veera')
),
'nolink' => array(
'id' => 'nolink',
'type' => 'switcher',
'title' => esc_html__("Don't link",'veera')
),
'only_icon' => array(
'id' => 'only_icon',
'type' => 'switcher',
'title' => esc_html__("Show Only Icon",'veera')
),
'hide' => array(
'id' => 'hide',
'type' => 'switcher',
'title' => esc_html__("Don't show a link",'veera')
),
'menu_type' => array(
'id' => 'menu_type',
'type' => 'select',
'title' => esc_html__('Menu Type','veera'),
'options' => array(
'narrow' => esc_html__('Narrow','veera'),
'wide' => esc_html__('Wide','veera')
),
'default' => 'narrow'
),
'submenu_position' => array(
'id' => 'submenu_position',
'type' => 'select',
'title' => esc_html__('SubMenu Position','veera'),
'info' => esc_html__('Apply for parent with "Menu Type" is "narrow"','veera'),
'options' => array(
'right' => esc_html__('Right','veera'),
'left' => esc_html__('Left','veera'),
),
'default' => 'right'
),
'force_full_width' => array(
'id' => 'force_full_width',
'type' => 'switcher',
'title' => esc_html__('Force Full Width','veera'),
'info' => esc_html__('Set 100% window width for popup','veera')
),
'popup_max_width' => array(
'id' => 'popup_max_width',
'type' => 'number',
'title' => esc_html__('Popup Max Width','veera'),
'after' => 'px',
'wrap_class' => 'la-element-popup-max-width'
),
'popup_column' => array(
'id' => 'popup_column',
'type' => 'select',
'title' => esc_html__('Popup Columns','veera'),
'options' => array(
'1' => esc_html__('1 Column','veera'),
'2' => esc_html__('2 Columns','veera'),
'3' => esc_html__('3 Columns','veera'),
'4' => esc_html__('4 Columns','veera'),
'5' => esc_html__('5 Columns','veera'),
'6' => esc_html__('6 Columns','veera')
),
'default' => '4'
),
'item_column' => array(
'id' => 'item_column',
'type' => 'text',
'title' => esc_html__('Columns','veera'),
'desc' => esc_html__('will occupy x columns of parent popup columns', 'veera')
),
'block' => array(
'id' => 'block',
'type' => 'select',
'title' => esc_html__('Custom Block Before Menu Item','veera'),
'options' => 'posts',
'query_args' => $query_args,
'default_option' => esc_html__('Select a block','veera')
),
'block2' => array(
'id' => 'block2',
'type' => 'select',
'title' => esc_html__('Custom Block After Menu Item','veera'),
'options' => 'posts',
'query_args' => $query_args,
'default_option' => esc_html__('Select a block','veera')
),
'popup_background' => array(
'id' => 'popup_background',
'type' => 'background',
'title' => esc_html__('Popup Background','veera')
),
'tip_label' => array(
'id' => 'tip_label',
'type' => 'text',
'title' => esc_html__('Tip Label','veera')
),
'tip_color' => array(
'id' => 'tip_color',
'type' => 'color_picker',
'title' => esc_html__('Tip Color','veera')
),
'tip_background_color' => array(
'id' => 'tip_background_color',
'type' => 'color_picker',
'title' => esc_html__('Tip Background','veera')
)
);
$this->load_hooks();
}
private function load_hooks(){
add_action( 'wp_loaded', array( $this, 'load_walker_edit' ), 9);
add_filter( 'wp_setup_nav_menu_item', array( $this, 'setup_nav_menu_item' ));
add_action( 'wp_nav_menu_item_custom_fields', array( $this, 'add_megamu_field_to_menu_item' ), 10, 4);
add_action( 'wp_update_nav_menu_item', array( $this, 'update_nav_menu_item' ), 10, 3);
add_filter( 'nav_menu_item_title', array( $this, 'add_icon_to_menu_item' ),10, 4);
add_filter( 'nav_menu_css_class', array( $this, 'nav_menu_css_class' ),10, 4);
}
public function load_walker_edit() {
add_filter( 'wp_edit_nav_menu_walker', array( $this, 'detect_edit_nav_menu_walker' ), 99 );
}
public function detect_edit_nav_menu_walker( $walker ) {
$walker = 'Veera_MegaMenu_Walker_Edit';
return $walker;
}
public function setup_nav_menu_item($menu_item){
$meta_value = Veera()->settings()->get_post_meta($menu_item->ID, '', $this->default_metakey, true);
foreach ( $this->fields as $key => $value ){
$menu_item->$key = isset($meta_value[$key]) ? $meta_value[$key] : '';
}
return $menu_item;
}
public function update_nav_menu_item( $menu_id, $menu_item_db_id, $menu_item_args ) {
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
return;
}
check_admin_referer( 'update-nav_menu', 'update-nav-menu-nonce' );
$key = $this->default_metakey;
if ( ! empty( $_POST[$key][$menu_item_db_id] ) ) {
$value = $_POST[$key][$menu_item_db_id];
}
else {
$value = null;
}
if(!empty($value)){
update_post_meta( $menu_item_db_id, $key, $value );
}
else {
delete_post_meta( $menu_item_db_id, $key );
}
}
public function add_megamu_field_to_menu_item( $id, $item, $depth, $args ) {
if(function_exists('la_fw_add_element')){
?>
<div class="lastudio-megamenu-settings description-wide la-content">
<h3><?php esc_html_e('MegaMenu Settings','veera');?></h3>
<div class="lastudio-megamenu-custom-fields">
<?php
foreach ( $this->fields as $key => $field ) {
$unique = $this->default_metakey . '['.$item->ID.']';
$default = ( isset( $field['default'] ) ) ? $field['default'] : '';
$elem_id = ( isset( $field['id'] ) ) ? $field['id'] : '';
$field['name'] = $unique. '[' . $elem_id . ']';
$field['id'] = $elem_id . '_' . $item->ID;
$elem_value = isset($item->$key) ? $item->$key : $default;
echo la_fw_add_element( $field, $elem_value, $unique );
}
?>
</div>
</div>
<?php
}
}
public function add_icon_to_menu_item($output, $item, $args, $depth){
if ( !is_a( $args->walker, 'Veera_MegaMenu_Walker' ) && $item->icon){
$icon_class = 'mm-icon ' . $item->icon;
$icon = "<i class=\"".esc_attr($icon_class)."\"></i>";
$output = $icon . $output;
}
return $output;
}
public function nav_menu_css_class( $classes, $item, $args, $depth ){
if(!is_a( $args->walker, 'Veera_MegaMenu_Walker' )){
if ( $item->hide ) {
$classes[] = "mm-item-hide";
}
if ( $item->nolink ) {
$classes[] = "mm-item-nolink";
}
if ( $item->only_icon ) {
$classes[] = "mm-item-onlyicon";
}
}
return $classes;
}
}
}
Can you please help me fix that? (Note: I am really newbie with those stuff, please be detailed)
I am sorry and thanks!

Can't use self in static method in php

I can't use self in a static method , it gives me this error message :
Fatal error: Using $this when not in object context in C:\xampp\htdocs\wordpress\wp-content\plugins\dw-usercp\usercp.php on line 136
here is the source code :
class dw_usercp
{
public static function plugin_activated() {
self::create_plugin_pages();
}
public function create_plugin_pages() {
$pages = array(
'signin' => array(
'title' => __( 'Sign In', 'dw-usercp' ),
'content' => '[dwusercp-sigin-form]',
'option_id' => 'login_page'
),
'user-account' => array(
'title' => __( 'Your Account', 'dw-usercp' ),
'content' => '[dwusercp-info]',
'option_id' => 'user_account_page'
),
'edit-user-info' => array(
'title' => __( 'Edit User Info', 'dw-usercp' ),
'content' => '[dwusercp-edit-info]',
'option_id' => 'user_editinfo_page'
),
'profile' => array(
'title' => __( 'User profile', 'dw-usercp' ),
'content' => '[dwusercp-profile]',
'option_id' => 'profile_page'
),
'signup' => array(
'title' => __( 'Sign Up', 'dw-usercp' ),
'content' => '[dwusercp-signup-form]',
'option_id' => 'register_page'
),
'user-lost-password' => array(
'title' => __( 'Forgot Your Password?', 'dw-usercp' ),
'content' => '[dwusercp-password-lost-form]',
'option_id' => 'lost_password_page'
),
'user-password-reset' => array(
'title' => __( 'Pick a New Password', 'dw-usercp' ),
'content' => '[dwusercp-password-reset-form]',
'option_id' => 'password_reset_page'
)
);
foreach( $pages as $slug => $page ) {
$query = new WP_Query( 'pagename=' . $slug );
if ( ! $query->have_posts() ) {
// Add the page using the data from the array above
$post_id = wp_insert_post(
array(
'post_content' => $page['content'],
'post_name' => $slug,
'post_title' => $page['title'],
'post_status' => 'publish',
'post_type' => 'page',
'ping_status' => 'closed',
'comment_status' => 'closed',
)
);
$this->update_plugin_option( $page['option_id'], $post_id ); // this is the line 136 that the error message says
}
}
}
/**
* Update plugin option
*
* #param string $field option id
* #param mixed $value option new value
* #return bool
*/
public function update_plugin_option( $field, $value ) {
$options = get_option("dw_usercp_options");
$options[$field] = $value;
update_option( "dw_usercp_options", $options );
}
}
$dw_usercp = new dw_usercp();
register_activation_hook( __FILE__, array( 'dw_usercp', 'plugin_activated' ) );
how do i call the create_plugin_pages() correctly then?
the plugin_activated() has to be static as Wordpress says
Inside a static function, you're not in an instance of the class. You could:
instantiate an instance of the class and call the function
Pass an instatiated object into the static funtion
Make the create_plugin_pagesfunction static and call it with static.
Convert plugin_activated to not be static (MY VOTE)
The static option won't work though since you call $this inside create_plugin_pages. So you'll need to go the instatiation route.
Non-static
public function plugin_activated() {
$this->create_plugin_pages();
}
Here's the passing in an object version
public static function plugin_activated(dw_usercp $a_dw_usercp) {
$a_dw_usercp->create_plugin_pages();
}
Its because you are using "$this" variable when you're in static context (did you read the error message?)
When in static context, use for methods:
self::method(args);
or
self::$attr for variables (attributes)
$this->update_plugin_option( $page['option_id'], $post_id );
is not self, as referenced in your title. You should be using:
self::update_plugin_option( $page['option_id'], $post_id );

Woocommerce - Change Widget to include Category

I use woocommerce and the standard widgets are fine, but I want to add the option to show products only from a certain category. Here is the code for the standard widget:
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* List products. One widget to rule them all.
*
* #author WooThemes
* #category Widgets
* #package WooCommerce/Widgets
* #version 2.3.0
* #extends WC_Widget
*/
class WC_Widget_Products extends WC_Widget {
/**
* Constructor
*/
public function __construct() {
$this->widget_cssclass = 'woocommerce widget_products';
$this->widget_description = __( 'Display a list of your products on your site.', 'woocommerce' );
$this->widget_id = 'woocommerce_products';
$this->widget_name = __( 'WooCommerce Products', 'woocommerce' );
$this->settings = array(
'title' => array(
'type' => 'text',
'std' => __( 'Products', 'woocommerce' ),
'label' => __( 'Title', 'woocommerce' )
),
'number' => array(
'type' => 'number',
'step' => 1,
'min' => 1,
'max' => '',
'std' => 5,
'label' => __( 'Number of products to show', 'woocommerce' )
),
'show' => array(
'type' => 'select',
'std' => '',
'label' => __( 'Show', 'woocommerce' ),
'options' => array(
'' => __( 'All Products', 'woocommerce' ),
'featured' => __( 'Featured Products', 'woocommerce' ),
'onsale' => __( 'On-sale Products', 'woocommerce' ),
)
),
'orderby' => array(
'type' => 'select',
'std' => 'date',
'label' => __( 'Order by', 'woocommerce' ),
'options' => array(
'date' => __( 'Date', 'woocommerce' ),
'price' => __( 'Price', 'woocommerce' ),
'rand' => __( 'Random', 'woocommerce' ),
'sales' => __( 'Sales', 'woocommerce' ),
)
),
'order' => array(
'type' => 'select',
'std' => 'desc',
'label' => _x( 'Order', 'Sorting order', 'woocommerce' ),
'options' => array(
'asc' => __( 'ASC', 'woocommerce' ),
'desc' => __( 'DESC', 'woocommerce' ),
)
),
'in_cat' => array(
'type' => 'text',
'std' => __( 'Category Number', 'woocommerce' ),
'label' => __( 'In Category', 'woocommerce' )
),
'hide_free' => array(
'type' => 'checkbox',
'std' => 0,
'label' => __( 'Hide free products', 'woocommerce' )
),
'show_hidden' => array(
'type' => 'checkbox',
'std' => 0,
'label' => __( 'Show hidden products', 'woocommerce' )
)
);
parent::__construct();
}
/**
* Query the products and return them
* #param array $args
* #param array $instance
* #return WP_Query
*/
public function get_products( $args, $instance ) {
$number = ! empty( $instance['number'] ) ? absint( $instance['number'] ) : $this->settings['number']['std'];
$show = ! empty( $instance['show'] ) ? sanitize_title( $instance['show'] ) : $this->settings['show']['std'];
$orderby = ! empty( $instance['orderby'] ) ? sanitize_title( $instance['orderby'] ) : $this->settings['orderby']['std'];
$order = ! empty( $instance['order'] ) ? sanitize_title( $instance['order'] ) : $this->settings['order']['std'];
$cat = ! empty( $instance['in_cat'] ) ? sanitize_title( $instance['in_cat'] ) : $this->settings['in_cat']['std'];
$query_args = array(
'posts_per_page' => $number,
'post_status' => 'publish',
'post_type' => 'product',
'no_found_rows' => 1,
'order' => $order,
'meta_query' => array(),
'post_type=products&cat='.$cat
);
if ( empty( $instance['show_hidden'] ) ) {
$query_args['meta_query'][] = WC()->query->visibility_meta_query();
$query_args['post_parent'] = 0;
}
if ( ! empty( $instance['hide_free'] ) ) {
$query_args['meta_query'][] = array(
'key' => '_price',
'value' => 0,
'compare' => '>',
'type' => 'DECIMAL',
);
}
$query_args['meta_query'][] = WC()->query->stock_status_meta_query();
$query_args['meta_query'] = array_filter( $query_args['meta_query'] );
switch ( $show ) {
case 'featured' :
$query_args['meta_query'][] = array(
'key' => '_featured',
'value' => 'yes'
);
break;
case 'onsale' :
$product_ids_on_sale = wc_get_product_ids_on_sale();
$product_ids_on_sale[] = 0;
$query_args['post__in'] = $product_ids_on_sale;
break;
}
switch ( $orderby ) {
case 'price' :
$query_args['meta_key'] = '_price';
$query_args['orderby'] = 'meta_value_num';
break;
case 'rand' :
$query_args['orderby'] = 'rand';
break;
case 'sales' :
$query_args['meta_key'] = 'total_sales';
$query_args['orderby'] = 'meta_value_num';
break;
default :
$query_args['orderby'] = 'date';
}
return new WP_Query( apply_filters( 'woocommerce_products_widget_query_args', $query_args ) );
}
/**
* widget function.
*
* #see WP_Widget
*
* #param array $args
* #param array $instance
*/
public function widget( $args, $instance ) {
if ( $this->get_cached_widget( $args ) ) {
return;
}
ob_start();
if ( ( $products = $this->get_products( $args, $instance ) ) && $products->have_posts() ) {
$this->widget_start( $args, $instance );
echo apply_filters( 'woocommerce_before_widget_product_list', '<ul class="product_list_widget">' );
while ( $products->have_posts() ) {
$products->the_post();
wc_get_template( 'content-widget-product.php', array( 'show_rating' => false ) );
}
echo apply_filters( 'woocommerce_after_widget_product_list', '</ul>' );
$this->widget_end( $args );
}
wp_reset_postdata();
echo $this->cache_widget( $args, ob_get_clean() );
}
}
As you can see I've added line 70:
'in_cat' => array(
'type' => 'text',
'std' => __( 'Category Number', 'woocommerce' ),
'label' => __( 'In Category', 'woocommerce' )
and also at Line 101:
$cat = ! empty( $instance['in_cat'] ) ? sanitize_title( $instance['in_cat'] ) : $this->settings['in_cat']['std'];
The option is available in the widget to be able to entera category ID and it saves when I click the save button.
The bit I'm struggling with is actually applying the filter, you will see i've added to Line 110:
'post_type=products&cat='.$cat
and I've also tried:
'category_name' => $cat
But I can't get the filters to work. Could anyone point me in the right direction please?
Cheers
Chris
Product category is custom taxonomy, you need to use 'tax_query' to solve the purpose as follows,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $cat,
),
),
Here, $cat should be string/array of taxonomy terms.
Even you can use, woocommerce shortcode if it suites your requirement,
[product_category category="appliances"]
Here, 'appliances' is slug of product category.

How to add categori selection option in theme option?

I am trying to add a category option in my wordpress theme using option tree. I am using this code in theme-option.php
<?php
$categories = get_categories('hide_empty=0&orderby=name');
$wp_cats = array();
foreach ($categories as $category_list ) {
$wp_cats[$category_list->cat_ID] = $category_list->cat_name;
}
add_action( 'admin_init', 'custom_theme_options', 1 );
function custom_theme_options() {
$saved_settings = get_option( 'option_tree_settings', array() );
$custom_settings = array(
'sections' => array(
array(
'id' => 'general',
'title' => 'Home Page Settings'
)
),
'settings' => array(
array(
'id' => 'Great-Product',
'label' => 'Great Product',
'desc' => 'select great Product category',
'type' => 'select',
'section' => 'general',
'std' => 'Choose a category',
'options' => $wp_cats
)
)
);
if ( $saved_settings !== $custom_settings ) {
update_option( 'option_tree_settings', $custom_settings );
}
}
?>
But it is not showing any category. Where is my fault? Please tell me.
You need to define $wp_cats variable within your function, or use global to bring it in.
Option 1 (global variable)
<?php
$categories = get_categories('hide_empty=0&orderby=name');
$wp_cats = array();
foreach ($categories as $category_list ) {
$wp_cats[$category_list->cat_ID] = $category_list->cat_name;
}
add_action( 'admin_init', 'custom_theme_options', 1 );
function custom_theme_options() {
global $wp_cats; /** GLOBAL!! */
$saved_settings = get_option( 'option_tree_settings', array() );
$custom_settings = array(
'sections' => array(
array(
'id' => 'general',
'title' => 'Home Page Settings'
)
),
'settings' => array(
array(
'id' => 'Great-Product',
'label' => 'Great Product',
'desc' => 'select great Product category',
'type' => 'select',
'section' => 'general',
'std' => 'Choose a category',
'options' => $wp_cats
)
)
);
if ( $saved_settings !== $custom_settings ) {
update_option( 'option_tree_settings', $custom_settings );
}
}
?>
Option 2 (build variable inside function)
<?php
add_action( 'admin_init', 'custom_theme_options', 1 );
function custom_theme_options() {
$categories = get_categories('hide_empty=0&orderby=name');
$wp_cats = array();
foreach ($categories as $category_list ) {
$wp_cats[$category_list->cat_ID] = $category_list->cat_name;
}
$saved_settings = get_option( 'option_tree_settings', array() );
$custom_settings = array(
'sections' => array(
array(
'id' => 'general',
'title' => 'Home Page Settings'
)
),
'settings' => array(
array(
'id' => 'Great-Product',
'label' => 'Great Product',
'desc' => 'select great Product category',
'type' => 'select',
'section' => 'general',
'std' => 'Choose a category',
'options' => $wp_cats
)
)
);
if ( $saved_settings !== $custom_settings ) {
update_option( 'option_tree_settings', $custom_settings );
}
}
?>
I have found the solution. Just need to write
'type' => 'category-select',
insted of
'type' => 'select',

Categories