// Add Featured Image to Post $image_url = 'http://s.wordpress.org/style/images/wp-header-logo.png'; // Define the image URL here $upload_dir = wp_upload_dir(); // Set upload folder $image_data = file_get_contents($image_url); // Get image data $filename = basename($image_url); // Create image file name // Check folder permission and define file location if( wp_mkdir_p( $upload_dir['path'] ) ) { $file = $upload_dir['path'] . '/' . $filename; } else { $file = $upload_dir['basedir'] . '/' . $filename; } // Create the image file on the server file_put_contents( $file, $image_data ); // Check image file type $wp_filetype = wp_check_filetype( $filename, null ); // Set attachment data $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name( $filename ), 'post_content' => '', 'post_status' => 'inherit' ); // Create the attachment $attach_id = wp_insert_attachment( $attachment, $file, $post_id ); // Include image.php require_once(ABSPATH . 'wp-admin/includes/image.php'); // Define attachment metadata $attach_data = wp_generate_attachment_metadata( $attach_id, $file ); // Assign metadata to attachment wp_update_attachment_metadata( $attach_id, $attach_data ); // And finally assign featured image to post set_post_thumbnail( $post_id, $attach_id );
// allow BGN for WooCommerce and PayPal add_filter( 'woocommerce_currencies', 'add_bgn_currency' ); function add_bgn_currency( $currencies ) { $currencies['BGN'] = __( 'Bulgarian Lev (лв.)', 'woocommerce' ); return $currencies; } add_filter('woocommerce_currency_symbol', 'add_bgn_currency_symbol', 10, 2); function add_bgn_currency_symbol( $currency_symbol, $currency ) { switch( $currency ) { case 'BGN': $currency_symbol = 'лв.'; break; } return $currency_symbol; } // allow BGN for WooCommerce and PayPal add_filter( 'woocommerce_paypal_supported_currencies', 'add_bgn_paypal_valid_currency' ); function add_bgn_paypal_valid_currency( $currencies ) { array_push ( $currencies , 'BGN' ); return $currencies; } // Convert BGN to EUR for PayPal payments add_filter('woocommerce_paypal_args', 'convert_bgn_to_eur'); function convert_bgn_to_eur($paypal_args){ if ( $paypal_args['currency_code'] == 'BGN'){ $convert_rate = 1.955; //set the converting rate $paypal_args['currency_code'] = 'EUR'; //change BGN to EUR $i = 1; while (isset($paypal_args['amount_' . $i])) { $paypal_args['amount_' . $i] = round( $paypal_args['amount_' . $i] / $convert_rate, 2); ++$i; } if ( $paypal_args['discount_amount_cart'] > 0 ) { $paypal_args['discount_amount_cart'] = round( $paypal_args['discount_amount_cart'] / $convert_rate, 2); } } return $paypal_args; }
Отворете functions.php на Вашата тема и поставете следния код:
require get_template_directory() . '/widgets/agenda.php';
agenda.php
<?php class agenda_widget extends WP_Widget { function agenda_widget() { parent::WP_Widget(false, $name = 'Get posts from different post types'); } function widget($args, $instance){ extract( $args ); $title = apply_filters('widget_title', $instance['title']); $posttype = $instance['posttype'] ? $instance['posttype'] : 'post'; $orderby = $instance['orderby'] ? $instance['orderby'] : 'ID'; $orderbyad = $instance['orderbyad'] ? $instance['orderbyad'] : 'ASC'; $limit = $instance['limit'] ? $instance['limit'] : 5; $bottom = $instance['bottom']; $args = array( 'posts_per_page' => $limit, 'orderby' => $orderby, 'order'=>$orderbyad, 'post_type' => $posttype); query_posts($args); $trainingen = get_posts( $args ); ?> <?php echo $before_widget; ?> <div class="widget-agenda"> <h3><?php echo $title ?></h3> <ul> <?php foreach ($trainingen as $training): ?> <?php if($training->dates) $dates = json_decode($training->dates) ?> <li><a href="<?php echo get_permalink($training->ID)?>"><?php //echo date_i18n(get_option("date_format"), strtotime($dates[0])) ?><?php _e($training->post_title); ?></a></li> <?php endforeach; ?> </ul> </div> <?php echo $after_widget; ?> <?php } function update($new_instance, $old_instance){ $instance = $old_instance; $instance['title'] = strip_tags($new_instance['title']); $instance['posttype'] = strip_tags($new_instance['posttype']); $instance['orderby'] = strip_tags($new_instance['orderby']); $instance['orderbyad'] = strip_tags($new_instance['orderbyad']); $instance['limit'] = strip_tags($new_instance['limit']); return $instance; } function form($instance){ $title = esc_attr($instance['title']); $posttype = esc_attr($instance['posttype']); $orderby = esc_attr($instance['orderby']); $orderbyad = esc_attr($instance['orderbyad']); $limit = esc_attr($instance['limit']); ?> <p> <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /> </p> <p> <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Select Post Type:'); ?></label> <? $args = array( 'public' => true, '_builtin' => false ); $output = 'names'; // names or objects, note names is the default $operator = 'and'; // 'and' or 'or' $post_types = get_post_types( $args, $output, $operator ); ?> <select id="<?php echo $this->get_field_id('posttype'); ?>" name="<?php echo $this->get_field_name('posttype'); ?>"> <option value="post" <? if ($posttype == 'post'){ ?>selected<? } ?>>post</option> <? foreach ( $post_types as $post_type ) { ?> <option value="<?=$post_type;?>" <? if ($posttype == $post_type){ ?>selected<? } ?>><?=$post_type;?></option> <? } ?> </select></br> <label for="<?php echo $this->get_field_id('orderby'); ?>"><?php _e('Order by'); ?></label>: <select id="<?php echo $this->get_field_id('orderby'); ?>" name="<?php echo $this->get_field_name('orderby'); ?>"> <option value="ID" <? if ($orderby == 'ID'){ ?>selected<? } ?>>ID</option> </select></br> <label for="<?php echo $this->get_field_id('orderbyad'); ?>"><?php _e('Order'); ?></label>: <select id="<?php echo $this->get_field_id('orderbyad'); ?>" name="<?php echo $this->get_field_name('orderbyad'); ?>"> <option value="ASC" <? if ($orderbyad == 'ASC'){ ?>selected<? } ?>>ASC</option> <option value="DESC" <? if ($orderbyad == 'DESC'){ ?>selected<? } ?>>DESC</option> </select> </p> <p> <label for="<?php echo $this->get_field_id('limit'); ?>"><?php _e('Limit'); ?></label> <input class="tiny-text" id="<?php echo $this->get_field_id('limit'); ?>" name="<?php echo $this->get_field_name('limit'); ?>" type="number" value="<?php echo $limit; ?>" /> </p> <?php } } add_action('widgets_init', create_function('', 'return register_widget("agenda_widget");')); ?>
Резултата от скрипта ще бъде следния:
Влезте в директорията на Вашата тема и поставете кода във файла functions.php:
require get_template_directory() . '/theme-options.php';
theme-options.php
<?php $themename = "Theme Option"; $shortname = "nt"; $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; } array_unshift($wp_cats, "Choose a category"); $options = array ( array( "name" => $themename." Options", "type" => "title"), array( "name" => "General", "type" => "section"), array( "type" => "open"), array( "name" => "Logo URL", "desc" => "Enter the link to your logo image", "id" => $shortname."_logo", "type" => "text", "std" => ""), array( "name" => "Portfolio", "desc" => "Check this option to turn on Portfolio Type", "id" => $shortname."_portfolio", "type" => "checkbox", "std" => ""), array( "name" => "Clone post", "desc" => "Check this option to turn on/off Clone Post option", "id" => $shortname."_clonepost", "type" => "checkbox", "std" => ""), array( "name" => "Google Fonts", "desc" => "Activate Google fonts integration", "id" => $shortname."_googlefonts", "type" => "checkbox", "std" => ""), array( "type" => "close"), array( "name" => "Theme Styles", "type" => "section"), array( "type" => "open"), array( "name" => "Colour Scheme", "desc" => "Select the colour scheme for the theme", "id" => $shortname."_color_scheme", "type" => "select", "options" => array("blue", "red", "green"), "std" => "blue"), array( "name" => "Colour Scheme Panel", "desc" => "Select the colour scheme for Panel", "id" => $shortname."_color_scheme_admin", "type" => "select", "options" => array("white", "black"), "std" => "white"), array( "name" => "Background color", "desc" => "", "id" => $shortname."_backgroundcolor", "type" => "text", "std" => ""), array( "name" => "Menu color", "desc" => "", "id" => $shortname."_menucolor", "type" => "text", "std" => ""), array( "name" => "Menu color hover", "desc" => "", "id" => $shortname."_menucolorhover", "type" => "text", "std" => ""), array( "name" => "Custom CSS", "desc" => "Want to add any custom CSS code? Put in here, and the rest is taken care of. This overrides any other stylesheets. eg: a.button{color:green}", "id" => $shortname."_custom_css", "type" => "textarea", "std" => ""), array( "type" => "close"), array( "name" => "Homepage", "type" => "section"), array( "type" => "open"), array( "name" => "Homepage header image", "desc" => "Enter the link to an image used for the homepage header.", "id" => $shortname."_header_img", "type" => "text", "std" => ""), array( "name" => "Homepage featured category", "desc" => "Choose a category from which featured posts are drawn", "id" => $shortname."_feat_cat", "type" => "select", "options" => $wp_cats, "std" => "Choose a category"), array( "type" => "close"), array( "name" => "Footer", "type" => "section"), array( "type" => "open"), array( "name" => "Position Fixed", "desc" => "Check this option to make footer position fixed", "id" => $shortname."_footerfixed", "type" => "checkbox", "std" => ""), array( "name" => "Footer copyright text", "desc" => "Enter text used in the right side of the footer. It can be HTML", "id" => $shortname."_footer_text", "type" => "textarea", "std" => ""), array( "name" => "Google Analytics Code", "desc" => "You can paste your Google Analytics or other tracking code in this box. This will be automatically added to the footer.", "id" => $shortname."_ga_code", "type" => "textarea", "std" => ""), array( "name" => "Custom Favicon", "desc" => "A favicon is a 16x16 pixel icon that represents your site; paste the URL to a .ico image that you want to use as the image", "id" => $shortname."_favicon", "type" => "text", "std" => get_bloginfo('url') ."/favicon.ico"), array( "name" => "Feedburner URL", "desc" => "Feedburner is a Google service that takes care of your RSS feed. Paste your Feedburner URL here to let readers see it in your website", "id" => $shortname."_feedburner", "type" => "text", "std" => get_bloginfo('rss2_url')), array( "type" => "close") ); function getmoonstyles(){ ?> <style > <? if (get_option( 'nt_footerfixed' )) { ?> .site-footer { position:fixed; z-index: 9999; } .site-content { margin-bottom: 60px; margin-top: 72px; } <? }else{ ?>.site-footer { position: inherit !important; } .site-content { margin-top: 72px; } <? } ?> </style> <? } function mytheme_add_admin() { global $themename, $shortname, $options; if ( $_GET['page'] == basename(__FILE__) ) { if ( 'save' == $_REQUEST['action'] ) { foreach ($options as $value) { update_option( $value['id'], $_REQUEST[ $value['id'] ] ); } foreach ($options as $value) { if( isset( $_REQUEST[ $value['id'] ] ) ) { update_option( $value['id'], $_REQUEST[ $value['id'] ] ); } else { delete_option( $value['id'] ); } } header("Location: admin.php?page=theme-options.php&saved=true"); die; } else if( 'reset' == $_REQUEST['action'] ) { foreach ($options as $value) { delete_option( $value['id'] ); } header("Location: admin.php?page=theme-options.php&reset=true"); die; } } add_menu_page($themename, $themename, 'administrator', basename(__FILE__), 'mytheme_admin'); } function mytheme_add_init() { $file_dir=get_bloginfo('template_directory'); //if (get_option( 'nt_color_scheme_admin' ) == 'white') //{ wp_enqueue_style("functions", $file_dir."/functions/functions_wt.css", false, "1.0", "all"); $logostyle = 'logo_wt.png'; //}else{ // wp_enqueue_style("functions", $file_dir."/functions/functions_bk.css", false, "1.0", "all"); // $logostyle = 'logo_bk.png'; // } wp_enqueue_script("rm_script", $file_dir."/functions/rm_script.js", false, "1.0"); } function mytheme_admin() { global $themename, $shortname, $options; $i=0; if ( $_REQUEST['saved'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings saved.</strong></p></div>'; if ( $_REQUEST['reset'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings reset.</strong></p></div>'; // if (get_option( 'nt_color_scheme_admin' ) == 'white') //{ $logostyle = 'logo_wt.png'; //}else{ // $logostyle = 'logo_bk.png'; // } ?> <div class="wrap rm_wrap"> <div class="themelogo"><img src="<?=get_template_directory_uri() . '/functions/images/'.$logostyle;?>"></div> <h2 class="zsd"><?php echo $themename; ?></h2> <div class="rm_opts"> <form method="post"> <?php foreach ($options as $value) { switch ( $value['type'] ) { case "open": ?> <?php break; case "close": ?> </div> </div> <br /> <?php break; case "title": ?> <div class="zsd2">To easily use the <?php echo $themename;?> theme, you can use the menu below.</div> <?php break; case 'text': ?> <div class="rm_input rm_text"> <label for="<?php echo $value['id']; ?>"><?php echo $value['name']; ?></label> <input name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" type="<?php echo $value['type']; ?>" value="<?php if ( get_settings( $value['id'] ) != "") { echo stripslashes(get_settings( $value['id']) ); } else { echo $value['std']; } ?>" /> <small><?php echo $value['desc']; ?></small><div class="clearfix"></div> </div> <?php break; case 'textarea': ?> <div class="rm_input rm_textarea"> <label for="<?php echo $value['id']; ?>"><?php echo $value['name']; ?></label> <textarea name="<?php echo $value['id']; ?>" type="<?php echo $value['type']; ?>" cols="" rows=""><?php if ( get_settings( $value['id'] ) != "") { echo stripslashes(get_settings( $value['id']) ); } else { echo $value['std']; } ?></textarea> <small><?php echo $value['desc']; ?></small><div class="clearfix"></div> </div> <?php break; case 'select': ?> <div class="rm_input rm_select"> <label for="<?php echo $value['id']; ?>"><?php echo $value['name']; ?></label> <select name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>"> <?php foreach ($value['options'] as $option) { ?> <option <?php if (get_settings( $value['id'] ) == $option) { echo 'selected="selected"'; } ?>><?php echo $option; ?></option><?php } ?> </select> <small><?php echo $value['desc']; ?></small><div class="clearfix"></div> </div> <?php break; case "checkbox": ?> <div class="rm_input rm_checkbox"> <label for="<?php echo $value['id']; ?>"><?php echo $value['name']; ?></label> <?php if(get_option($value['id'])){ $checked = "checked=\"checked\""; }else{ $checked = "";} ?> <input type="checkbox" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" value="true" <?php echo $checked; ?> /> <small><?php echo $value['desc']; ?></small><div class="clearfix"></div> </div> <?php break; case "section": $i++; ?> <div class="rm_section"> <div class="rm_title"><h3><img src="<?php bloginfo('template_directory')?>/functions/images/trans.png" class="inactive" alt="""><?php echo $value['name']; ?></h3><span class="submit"><input name="save<?php echo $i; ?>" type="submit" value="Save changes" /> </span><div class="clearfix"></div></div> <div class="rm_options" style=" display:none;"> <?php break; } } ?> <input type="hidden" name="action" value="save" /> </form> <form method="post"> <p class="submit"> <input name="reset" type="submit" value="Reset Theme Options" /> <input type="hidden" name="action" value="reset" /> </p> </form> <div class="fns">Panel & Theme creation by <a href="http://atanasfilipov.com/" target="_blank">Atanasfilipov.com</a></div> </div> <?php } ?> <?php add_action('admin_init', 'mytheme_add_init'); add_action('admin_menu', 'mytheme_add_admin'); ?>
Създайте папка functions, и в нея създайте следните файлове: functions_bk.css, functions_wt.css, rm_script.js:
functions_bk.css
.rm_wrap, .rm_wrap h2, .rm_wrap p, .rm_options { background: #000000; color: #ffffff; padding: 20px; } .rm_wrap h2 { font-size: 35px; } .rm_wrap { width: 80%; margin-left: auto; margin-right: auto; } .fns { font-size: 10px; text-align: center; } .fns a { color: #678fbf; text-decoration: none; } .fns a:hover { text-decoration: underline; } .zsd{ text-align:center; } .zsd2{ margin-bottom:10px; text-transform: lowercase; } .rm_opts{ text-align:left; } .rm_section{ border:1px solid #333; border-bottom:0; background:#f9f9f9; } .rm_opts label{ font-size:16px; width:200px; display:block; float:left; } .rm_input { padding:30px 10px; border-bottom:1px solid #333; } .rm_opts small{ display:block; float:right; width:40%; color:#ffffff; font-size:14px; text-align:left; } .rm_opts input[type="text"], .rm_opts select{ width:280px; font-size:12px; padding:4px; color:#333; line-height:1em; background:#f3f3f3; } .rm_input input:focus, .rm_input textarea:focus{ background:#fff; } .rm_input textarea{ width:280px; height:175px; font-size:12px; padding:4px; color:#333; line-height:1.5em; background:#f3f3f3; } .rm_title h3 { cursor:pointer; font-size:20px; text-transform: uppercase; margin:0; font-weight:bold; color:#ffffff; float:left; width:80%; padding:14px 4px; } .rm_title{ cursor:pointer; background:url('images/backtheme.png'); padding:0; } .rm_title h3 img.inactive{ margin:-8px 10px 0 2px; width:32px; height:32px; background:url('images/pointer.png') no-repeat 0 0; float:left; -moz-border-radius:6px; } .rm_title h3 img.active{ margin:-8px 10px 0 2px; width:32px; height:32px; background:url('images/pointer.png') no-repeat 0 -32px; float:left; } .rm_title{ border:1px solid #222222; } .rm_title:hover{ border:1px solid #678fc0; } .rm_title span.submit{ display: block; float: right; margin: 0; padding: 0; width: 15%; padding: 14px 0; text-align: center; } .submit input { background: #222222; color: #f25757; border: #2E2D2D 1px solid; font-size: 14px; padding-left: 10px; padding-right: 10px; -moz-border-radius: 5px 5px 5px 5px; border-radius: 5px 5px 5px 5px; } .submit input:hover { cursor: pointer; cursor: hand; background: #000000; } #message strong{ color:#e51865; } .rm_wrap #message p { margin: 0 !important; } .clearfix{ clear:both; } .rm_table th, .rm_table td{ border:1px solid #bbb; padding:10px; text-align:center; } .themelogo{ text-align:left; position:absolute; top:0; } .themelogo img{ height:150px; } .rm_table th, .rm_table td.feature{ border-color:#888; } .notice, div.error, div.updated { background: none; } .notice-success, div.updated { border-left-color: #fb2b79; background: #fb2b79; } .notice-success, div.updated p { padding-left:20px; }
functions_wt.css
.rm_wrap, .rm_wrap h2, .rm_wrap p, .rm_options { background: #ffffff; color: #000000; padding: 20px; } .rm_wrap h2 { font-size: 35px; } .rm_wrap { width: 80%; margin-left: auto; margin-right: auto; } .fns { font-size: 10px; text-align: center; } .fns a { color: #678fbf; text-decoration: none; } .fns a:hover { text-decoration: underline; } .zsd{ text-align:center; } .zsd2{ margin-bottom:10px; text-transform: lowercase; } .rm_opts{ text-align:left; } .rm_section{ border-bottom:0; background:#f9f9f9; } .rm_opts label{ font-size:16px; width:200px; display:block; float:left; } .rm_input { padding:30px 10px; border: #e9e9e9 1px solid; } .rm_opts small{ display:block; float:right; width:40%; color:#000000; font-size:14px; text-align:left; } .rm_opts input[type="text"], .rm_opts select{ width:280px; font-size:12px; padding:4px; color:#333; line-height:1em; background:#f3f3f3; } .rm_input input:focus, .rm_input textarea:focus{ background:#fff; } .rm_input textarea{ width:280px; height:175px; font-size:12px; padding:4px; color:#333; line-height:1.5em; background:#f3f3f3; } .rm_title h3 { cursor:pointer; font-size:20px; text-transform: uppercase; margin:0; font-weight:bold; color:#000000; float:left; width:80%; padding:14px 4px; } .rm_title{ cursor:pointer; background:url('images/backtheme_wt.png'); padding:0; } .rm_title h3 img.inactive{ margin:-8px 10px 0 2px; width:32px; height:32px; background:url('images/pointer.png') no-repeat 0 0; float:left; -moz-border-radius:6px; } .rm_title h3 img.active{ margin:-8px 10px 0 2px; width:32px; height:32px; background:url('images/pointer.png') no-repeat 0 -32px; float:left; } .rm_title{ border:1px solid #e9e9e9; } .rm_title:hover{ border:1px solid #678fc0; } .rm_title span.submit{ display: block; float: right; margin: 0; padding: 0; width: 15%; padding: 14px 0; text-align: center; } .submit input { background: #fff; color: #f25757; border: #e9e9e9 1px solid; font-size: 14px; padding-left: 10px; padding-right: 10px; -moz-border-radius: 5px 5px 5px 5px; border-radius: 5px 5px 5px 5px; font-weight:bold; } .submit input:hover { cursor: pointer; cursor: hand; background: #e9e9e9; } #message strong{ color:#e51865; } .rm_wrap #message p { margin: 0 !important; } .clearfix{ clear:both; } .rm_table th, .rm_table td{ border:1px solid #bbb; padding:10px; text-align:center; } .themelogo{ text-align:left; position:absolute; top:0; } .themelogo img{ height:150px; } .rm_table th, .rm_table td.feature{ border-color:#888; } .notice, div.error, div.updated { background: none; } .notice-success, div.updated { border-left-color: #fb2b79; background: #fb2b79; } .notice-success, div.updated p { padding-left:20px; }
rm_script.js
jQuery(document).ready(function(){ jQuery('.rm_options').slideUp(); jQuery('.rm_section h3').click(function(){ if(jQuery(this).parent().next('.rm_options').css('display')=='none') { jQuery(this).removeClass('inactive'); jQuery(this).addClass('active'); jQuery(this).children('img').removeClass('inactive'); jQuery(this).children('img').addClass('active'); } else { jQuery(this).removeClass('active'); jQuery(this).addClass('inactive'); jQuery(this).children('img').removeClass('active'); jQuery(this).children('img').addClass('inactive'); } jQuery(this).parent().next('.rm_options').slideToggle('slow'); }); });
И последно, свалете и картинките към скрипта и ги поставете в директорията на Вашата тема/functions/images/. Свали картинките от тук.
// Remove WP Version From Styles add_filter( 'style_loader_src', 'sdt_remove_ver_css_js', 9999 ); // Remove WP Version From Scripts add_filter( 'script_loader_src', 'sdt_remove_ver_css_js', 9999 ); // Function to remove version numbers function sdt_remove_ver_css_js( $src ) { if ( strpos( $src, 'ver=' ) ) $src = remove_query_arg( 'ver', $src ); return $src; }
add_action('restrict_manage_posts','my_restrict_manage_posts'); function my_restrict_manage_posts() { global $typenow; if ($typenow=='job_listing'){ $args = array( 'show_option_all' => "Show All Cities", 'taxonomy' => 'listing_cities', 'name' => 'listing_cities' ); wp_dropdown_categories($args); } } add_action( 'request', 'my_request' ); function my_request($request) { if (is_admin() && $GLOBALS['PHP_SELF'] == '/wp-admin/edit.php' && isset($request['post_type']) && $request['post_type']=='job_listing') { $request['listing_cities'] = get_term($request['listing_cities'],'listing_cities')->name; } return $request; }
Send email
$data = @$_POST; $err = array(); if(!empty($_POST)){ if(empty($_POST["your_name"])){ $err["your_name"] = true; } if(empty($_POST["your_email"])){ $err["your_email"] = true; } if(empty($_POST["your_subject"])){ $err["your_subject"] = true; } if(empty($_POST["your_message"])){ $err["your_message"] = true; } if(empty($err)){ $your_name = strip_tags($_POST["your_name"]); $your_company = strip_tags($_POST["your_company"]); $your_phone = strip_tags($_POST["your_phone"]); $your_email = strip_tags($_POST["your_email"]); $your_subject = strip_tags($_POST["your_subject"]); $your_message = strip_tags($_POST["your_message"]); $caption = "Contactform"; $admin_email = get_option("admin_email"); ob_start(); include("template-contact-mail.php"); $mail_content = ob_get_contents(); ob_end_clean() ; $headers = 'Content-Type: text/html; charset=UTF-8'.'\r\n'; $headers .= 'From: '.$your_name.' <'.$your_email.'>' . "\r\n"; $success = wp_mail($admin_email, $caption, $mail_content, $headers); header("Location: ".get_permalink(PAGE_ID_SUCCESS_CONTACT)); die; } }
<form action="" method="post" class="wpcf7-form"> <p<?php if(!empty($err["your_name"])): ?> class="err"<?php endif; ?>> <label><?php _e("Your name") ?> (*):</label> <span class="wpcf7-form-control-wrap"><input type="text" name="your_name" value="<?php echo $data["your_name"] ?>" size="40" class="wpcf7-form-control wpcf7-text" /></span> </p> <p<?php if(!empty($err["your_company"])): ?> class="err"<?php endif; ?>> <label><?php _e("Company") ?>:</label> <span class="wpcf7-form-control-wrap"><input type="text" name="your_company" value="<?php echo $data["your_company"] ?>" size="40" class="wpcf7-form-control wpcf7-text" /></span> </p> <p<?php if(!empty($err["your_phone"])): ?> class="err"<?php endif; ?>> <label><?php _e("Phone") ?>:</label> <span class="wpcf7-form-control-wrap"><input type="text" name="your_phone" value="<?php echo $data["your_phone"] ?>" size="40" class="wpcf7-form-control wpcf7-text" /></span> </p> <p<?php if(!empty($err["your_email"])): ?> class="err"<?php endif; ?>> <label><?php _e("Email") ?> (*):</label> <span class="wpcf7-form-control-wrap"><input type="email" name="your_email" value="<?php echo $data["your_email"] ?>" size="40" class="wpcf7-form-control wpcf7-text" /></span> </p> <p<?php if(!empty($err["your_subject"])): ?> class="err"<?php endif; ?>> <label><?php _e("Subject") ?> (*):</label> <span class="wpcf7-form-control-wrap"><input type="text" name="your_subject" value="<?php echo $data["your_subject"] ?>" size="40" class="wpcf7-form-control wpcf7-text" /></span> </p> <p<?php if(!empty($err["your_message"])): ?> class="err"<?php endif; ?>> <label><?php _e("Message") ?> (*):</label> <span class="wpcf7-form-control-wrap"><textarea name="your_message" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea"><?php echo $data["your_message"] ?></textarea></span> </p> <p> <input type="submit" value="submit" class="wpcf7-form-control wpcf7-submit" /> </p> </form>
template-contact-mail.php
<br />Onderwerp: <?php echo $caption ?> <br /> <br />NAME: <br /><?php echo $your_name ?> <br /> <br />COMPANY: <br /><?php echo $your_company ?> <br /> <br />PHONE: <br /><?php echo $your_phone ?> <br /> <br />E-MAIL ADDRESS: <br /><?php echo $your_email ?> <br /> <br />SUBJECT: <br /><?php echo $your_subject ?> <br /> <br />MESSAGE: <br /><?php echo $your_message ?> <br /> <br />-- <br />atanasfilipov.com
Индекс на базата ( http://example.com/faq/
) [Индекс на цялата база]
- Основна категория (
http://example.com/faq/category/
) [Индекс на Основната категория]- Публикация в основната категория (
http://example.com/faq/category/post-1-slug/
) [Преглед на Публикация 1] - Под-категория (
http://example.com/faq/category/sub-category/
) [Индекс на под-категорията]- Публикация в под-категорията (
http://example.com/faq/category/sub-category/post-2-slug/
) [Преглед на Публикация 2]
- Публикация в под-категорията (
- Публикация в основната категория (
- Друга основна категория (
http://example.com/faq/another-category/
) [Индекс на другата основна категория]
Всичко изглежда нормално(като структура на линковете) за нормалния потребител, обаче WordPress е на друго мнение по въпроса Вместо линк като http://example.com/faq/category/
ние ще можем да видим индекса на основната категория на линк от рода на http://example.com/faq-category/category/
. Което както виждате не съвпада съвсем с първоначалната идея. За да оправим този проблем трябва да прибегнем до добавянето на няколко специално написани Permalink правила и функции.
Първата стъпка е да регистрираме новия пост тип(Custom Post Type). Това се случва със следната функция:
<?php add_action( 'init', 'register_faq_post_type' ); function register_faq_post_type() { register_post_type( 'faq', array( 'labels' => array( 'name' => 'Frequently Asked Questions', 'menu_name' => 'FAQ Manager', 'singular_name' => 'Question', 'all_items' => 'All Questions' ), 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'show_in_nav_menus' => true, 'menu_position ' => 20, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'comments', 'post-formats', 'revisions' ), 'hierarchical' => false, 'has_archive' => 'faq', 'rewrite' => array( 'slug' => 'faq-item', 'hierarchical' => true, 'with_front' => false ) ) ); register_taxonomy( 'faq-category', array( 'faq' ), array( 'labels' => array( 'name' => 'FAQ Categories', 'menu_name' => 'FAQ Categories', 'singular_name' => 'FAQ Category', 'all_items' => 'All Categories' ), 'public' => true, 'hierarchical' => true, 'show_ui' => true, 'rewrite' => array( 'slug' => 'faq-category', 'hierarchical' => true, 'with_front' => false ), ) ); } ?>
Този код ще регистрира новия пост тип, заедно с новата таксономия „FAQ Categories“, която ще използваме за да категоризираме въпросите.
След като регистрираме новия пост тип остава да добавим две функции които да направят така че Permalink-овете да работят както искаме ние
<?php add_action( 'generate_rewrite_rules', 'register_faq_rewrite_rules' ); function register_faq_rewrite_rules( $wp_rewrite ) { $new_rules = array( 'faq/([^/]+)/?$' => 'index.php?faq-category=' . $wp_rewrite->preg_index( 1 ), 'faq/([^/]+)/([^/]+)/?$' => 'index.php?post_type=faq&faq-category=' . $wp_rewrite->preg_index( 1 ) . '&faq=' . $wp_rewrite->preg_index( 2 ), 'faq/([^/]+)/([^/]+)/page/(\d{1,})/?$' => 'index.php?post_type=faq&faq-category=' . $wp_rewrite->preg_index( 1 ) . '&paged=' . $wp_rewrite->preg_index( 3 ), 'faq/([^/]+)/([^/]+)/([^/]+)/?$' => 'index.php?post_type=faq&faq-category=' . $wp_rewrite->preg_index( 2 ) . '&faq=' . $wp_rewrite->preg_index( 3 ), ); $wp_rewrite->rules = $new_rules + $wp_rewrite->rules; } // A hacky way of adding support for flexible custom permalinks // There is one case in which the rewrite rules from register_kb_rewrite_rules() fail: // When you visit the archive page for a child section(for example: http://example.com/faq/category/child-category) // The deal is that in this situation, the URL is parsed as a Knowledgebase post with slug "child-category" from the "category" section function fix_faq_subcategory_query($query) { if ( isset( $query['post_type'] ) && 'faq' == $query['post_type'] ) { if ( isset( $query['faq'] ) && $query['faq'] && isset( $query['faq-category'] ) && $query['faq-category'] ) { $query_old = $query; // Check if this is a paginated result(like search results) if ( 'page' == $query['faq-category'] ) { $query['paged'] = $query['name']; unset( $query['faq-category'], $query['name'], $query['faq'] ); } // Make it easier on the DB $query['fields'] = 'ids'; $query['posts_per_page'] = 1; // See if we have results or not $_query = new WP_Query( $query ); if ( ! $_query->posts ) { $query = array( 'faq-category' => $query['faq'] ); if ( isset( $query_old['faq-category'] ) && 'page' == $query_old['faq-category'] ) { $query['paged'] = $query_old['name']; } } } } return $query; } add_filter( 'request', 'fix_faq_subcategory_query', 10 ); ?>
В горния код регистрираме две функции – register_faq_rewrite_rules()
и fix_faq_subcategory_query()
.
Първата функция добавя следните няколко правила:
faq/([^/]+)/?$
– това правило ще бъде приложено когато адреса на страницата която се зарежда прилича на „faq/any-character/“ – тоест когато имаме начална част „faq/“ последвана от всякаква комбинация от символи, без „/“( „([^/]+)“ ), евентуално последвана от „/“( „/?“ ). Също така тази част трябва да е последната част от адреса на страницата, за да има съвпадение(т.е. няма да има съвпадение, ако адреса е „faq/any-character/something“).Когато адреса съвпадне, на текущата страница ще бъде показан архив за категорията(според примера който дадох по-горе) „any-character“.faq/([^/]+)/([^/]+)/?$
– това правило е почти същото като предишното, с изключение на това че вече адреса който би съвпаднал би изглеждал като „faq/any-character/post-slug/“.Това ще зареди публикация с кратко име(slug) „post-slug“ от категорията за ЧЗВ с кратко име „any-character“.faq/([^/]+)/([^/]+)/([^/]+)/?$
– това правило е почти същото като предишното, с изключение на това че вече адреса който би съвпаднал би изглеждал като „faq/any-character/sub-category/post-slug/“.Това ще зареди публикация с кратко име(slug) „post-slug“ от категорията за ЧЗВ с кратко име „sub-category“.
Втората функция от друга страна оправя проблема със под-категориите. А самият проблем се състои в това, че когато се опитате да заредите страница с адрес faq/category/child-category/
, WordPress ще се опита да зареди публикация с кратко име „child-category“ вместо под-категорията с кратко име „child-category“. Самата функция е по всяка вероятност не най-красивото решение на проблема, най-малкото защото трябва да направим една допълнителна заявка към базата данни, но това е единствения начин по който успях да реша проблема Понеже функцията проверява дали има публикации с краткото име „child-category“, ако случайно има такава публикация, може да получите неочаквани резултати
Това е достатъчно за да подкарате секцията за ЧЗВ, обаче в момента ако искате да използвате пълноценно новите адреси на категориите и публикациите, ще трябва да си ги пишете сами. Това е защото WordPress не знае как трябва да генерира линковете така че да съвпадат с нашата идея. За това добавяме още няколко функции:
<?php function faq_article_permalink( $article_id, $section_id = false, $leavename = false, $only_permalink = false ) { $taxonomy = 'faq-category'; $article = get_post( $article_id ); $return = '<a href="'; $permalink = ( $section_id ) ? trailingslashit( get_term_link( intval( $section_id ), 'faq-category' ) ) : home_url( '/faq/' ); $permalink .= trailingslashit( ( $leavename ? "%$article->post_type%" : $article->post_name ) ); $return .= $permalink . '/" >' . get_the_title( $article->ID ) . '</a>'; return ( $only_permalink ) ? $permalink : $return; } function filter_faq_post_link( $permalink, $post, $leavename ) { if ( get_post_type( $post->ID ) == 'faq' ) { $terms = wp_get_post_terms( $post->ID, 'faq-category' ); $term = ( $terms ) ? $terms[0]->term_id : false; $permalink = faq_article_permalink( $post->ID, $term, $leavename, true ); } return $permalink; } add_filter( 'post_type_link', 'filter_faq_post_link', 100, 3 ); function filter_faq_section_terms_link( $termlink, $term, $taxonomy = false ) { if ( $taxonomy == 'faq-category' ) { $section_ancestors = get_ancestors( $term->term_id, $taxonomy ); krsort( $section_ancestors ); $termlink = home_url( '/faq/' ); foreach ( $section_ancestors as $ancestor ) { $section_ancestor = get_term( $ancestor, $taxonomy ); $termlink .= $section_ancestor->slug . '/'; } $termlink .= trailingslashit( $term->slug ); } return $termlink; } add_filter( 'term_link', 'filter_faq_section_terms_link', 100, 3 ); ?>
Горните функции „филтрират“ резултата от две вградени в WordPress функции, които се грижат да създадат правилните линкове за всички страници, публикации и архиви на таксономии.
Остава един проблем, който може да не е никак малък за някои потребители – проблема с дубликиращото се съдържание. Има доста голяма вероятност Google или някоя друга търсачка която обхожда сайта ви да не остане очарована от факта, че намира идентично съдържание на два различни адреса(например faq-item/post-2-slug/
и faq/category/sub-category/post-2-slug/
). Това може да се избегне с една функция която да препраща потребителите към правилния адрес, но оставям това на вас.
Източник: http://themoonwatch.com/bg/%D0%BA%D0%B0%D1%82%D0%B5%D0%B3%D0%BE%D1%80%D0%B8%D1%8F/php-i-wordpress/#sthash.GBKCWoNy.dpuf
– qTranslate X
– Loco Translate
– Contact Form 7
– WP Google Map Plugin
– Google Analytics for WordPress
– WordPress SEO
– Google XML Sitemaps
– Advanced Custom Fields
– Meta Slider
– WooCommerce *
– Contact Form DB
– WP Lightbox 2
– Background Per Page
– WYSIWYG Widgets / Widget Blocks
– HC Text Widget
– Gallery
– WP Simple Galleries
– TinyMCE Advanced
– Disable Comments
– Simple 301 Redirects
– YouTube SimpleGallery
– Share Buttons by AddToAny
– Resize Image After Upload
– Imsanity
– Category Order and Taxonomy Terms Order