Ето и кода, който трябва да поставите в function.php на вашата тема:
class mishaDateRange{ function __construct(){ // if you do not want to remove default "by month filter", remove/comment this line add_filter( 'months_dropdown_results', '__return_empty_array' ); // include CSS/JS, in our case jQuery UI datepicker add_action( 'admin_enqueue_scripts', array( $this, 'jqueryui' ) ); // HTML of the filter add_action( 'restrict_manage_posts', array( $this, 'form' ) ); // the function that filters posts add_action( 'pre_get_posts', array( $this, 'filterquery' ) ); } /* * Add jQuery UI CSS and the datepicker script * Everything else should be already included in /wp-admin/ like jquery, jquery-ui-core etc * If you use WooCommerce, you can skip this function completely */ function jqueryui(){ wp_enqueue_style( 'jquery-ui', '//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css' ); wp_enqueue_script( 'jquery-ui-datepicker' ); } /* * Two input fields with CSS/JS * If you would like to move CSS and JavaScript to the external file - welcome. */ function form(){ $from = ( isset( $_GET['mishaDateFrom'] ) && $_GET['mishaDateFrom'] ) ? $_GET['mishaDateFrom'] : ''; $to = ( isset( $_GET['mishaDateTo'] ) && $_GET['mishaDateTo'] ) ? $_GET['mishaDateTo'] : ''; echo ' '; } /* * The main function that actually filters the posts */ function filterquery( $admin_query ){ global $pagenow; if ( is_admin() && $admin_query->is_main_query() // by default filter will be added to all post types, you can operate with $_GET['post_type'] to restrict it for some types && in_array( $pagenow, array( 'edit.php', 'upload.php' ) ) && ( ! empty( $_GET['mishaDateFrom'] ) || ! empty( $_GET['mishaDateTo'] ) ) ) { $admin_query->set( 'date_query', // I love date_query appeared in WordPress 3.7! array( 'after' => sanitize_text_field( $_GET['mishaDateFrom'] ), // any strtotime()-acceptable format! 'before' => sanitize_text_field( $_GET['mishaDateTo'] ), 'inclusive' => true, // include the selected days as well 'column' => 'post_date' // 'post_modified', 'post_date_gmt', 'post_modified_gmt' ) ); } return $admin_query; } } new mishaDateRange();
Как да направим филтър на поръчки в администрацията на WooCommerce по персонализирано поле или Custom Field, който сме създали в нашите order-и (в случая post_type-а е shop_order):
1. Нека първо да направим функцията, която ще промени главната заявка и тя да се стартира само, когато typenow е ‘shop_order’. В случая следим променливата paybyw дали е равна на “on” и ще филтрираме по този критерии.
function so_filter_shop_order3($query) { global $typenow; $user = wp_get_current_user(); if ($query->is_main_query() && $typenow === 'shop_order') { $query->set( 'meta_key', 'paybyw' ); $query->set( 'meta_value', 'on' ); } }
2. Следим, дали сесията ни е я има и въз основа на стойността й включваме или изключваме дадена функция.
if ($_GET['order_type']) { $_SESSION["order_type"] = (int)$_GET['order_type']; }elseif ($_GET['order_type'] == '0') { $_SESSION["order_type"] = 0; } switch ($_SESSION["order_type"]) { case 0: break; case 3: add_action( 'pre_get_posts', 'so_filter_shop_order3' ); break; case 4: add_action( 'pre_get_posts', 'so_filter_shop_order4' ); break; case 5: add_action( 'pre_get_posts', 'so_filter_shop_order5' ); break; }
Скоро ми се случи в един мой WP сайт, да се обърна към друг и да извадя информация от базата данни и ето как го направих:
Първо създадох функция за връзка с базата данни на втория сайт:
function seconddb() { global $seconddb; $seconddb = new wpdb(USERNAME, PASSWORD, DATABASE_NAME, HOSTNAME); } add_action('init', 'seconddb');
След това си написах shortcode, който да мога да включа където искам в първия сайт и да визуализирам данните от втория:
function ajaxloadcatalog_func( $atts ){ global $seconddb; $text = ''; $allcats = $seconddb->get_results( "SELECT t.term_id AS id, t.name AS post_title, t.slug AS post_url FROM vcp_terms t LEFT JOIN vcp_term_taxonomy tt ON t.term_id = tt.term_id WHERE tt.taxonomy = 'product_cat' ORDER BY name "); foreach ( $allcats as $mycats ) { $text .= $mycats->post_url.' - '.$mycats->post_title; } return $text; } add_shortcode( 'ajaxloadcatalog', 'ajaxloadcatalog_func' );
Как да търсим в нашата WordPress система по точно определена ключова дума?
Чрез този код, ако търсите думата “спорт”, то пост в който има думата “автотранспорт” няма да излезе. Ще излязат всички постове, в които съществува точно думата “спорт” и тя не е част от друга дума.
add_filter('posts_search', 'my_search_is_exact', 20, 2); function my_search_is_exact($search, $wp_query){ global $wpdb; if(empty($search)) return $search; $q = $wp_query->query_vars; $n = !empty($q['exact']) ? '' : '%'; $search = $searchand = ''; foreach((array)$q['search_terms'] as $term) : $term = esc_sql(like_escape($term)); $search.= "{$searchand}($wpdb->posts.post_title REGEXP '[[:<:]]{$term}[[:>:]]') OR ($wpdb->posts.post_content REGEXP '[[:<:]]{$term}[[:>:]]')"; $searchand = ' AND '; endforeach; if(!empty($search)) : $search = " AND ({$search}) "; if(!is_user_logged_in()) $search .= " AND ($wpdb->posts.post_password = '') "; endif; return $search; }
1. Инсталирайте следния модул: Rename wp-login.php, след това направете login варианта на вашия сайт.
2. Отворете functions.php файла на темата, която ползвате и напишете следните редове:
if (($_SERVER['PHP_SELF'] == '/wp-admin/index.php')and( !is_super_admin() )) { wp_redirect( home_url() ); exit(); }
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' ); function custom_override_checkout_fields( $fields ) { unset($fields['billing']['billing_first_name']); unset($fields['billing']['billing_last_name']); unset($fields['billing']['billing_company']); unset($fields['billing']['billing_address_1']); unset($fields['billing']['billing_address_2']); unset($fields['billing']['billing_city']); unset($fields['billing']['billing_postcode']); unset($fields['billing']['billing_country']); unset($fields['billing']['billing_state']); unset($fields['billing']['billing_phone']); unset($fields['order']['order_comments']); unset($fields['billing']['billing_address_2']); unset($fields['billing']['billing_postcode']); unset($fields['billing']['billing_company']); unset($fields['billing']['billing_last_name']); unset($fields['billing']['billing_email']); unset($fields['billing']['billing_city']); return $fields; }