В примера по-долу извиквам Media Library на WordPress, чрез натискане на картинка.
<script> function getmedia(ident){ // Instantiates the variable that holds the media library frame. var meta_image_frame; // Runs when the image button is clicked. j(function(){ // Prevents the default action from occuring. // e.preventDefault(); // If the frame already exists, re-open it. if ( meta_image_frame ) { meta_image_frame.open(); return; } // Sets up the media library frame meta_image_frame = wp.media.frames.meta_image_frame = wp.media({ // title: meta_image.title, // button: { text: meta_image.button }, library: { type: 'image' } }); // Runs when an image is selected. meta_image_frame.on('select', function(){ // return false; // Grabs the attachment selection and creates a JSON representation of the model. var media_attachment = meta_image_frame.state().get('selection').first().toJSON(); // Sends the attachment URL to our custom image input field. document.getElementById("imgc_"+ident).src = media_attachment.sizes.thumbnail.url; //media_attachment.id; имате и id-то на самият attachment (за повече опции, проверете в WordPress документацията) }); // Opens the media library frame. meta_image_frame.open(); }); } </script>
Ето това са картинките, чрез които ще извикваме Media Library и ще заменяме src адреса.
<img src="smiley.gif" id="imgc_1" alt="Smiley face" height="42" width="42" onclick="getmedia('1');"></br> <img src="smiley.gif" id="imgc_2" alt="Smiley face" height="42" width="42" onclick="getmedia('2');"></br> <img src="smiley.gif" id="imgc_3" alt="Smiley face" height="42" width="42" onclick="getmedia('3');">
<?php // Add term page function pippin_taxonomy_add_new_meta_field() { // this will add the custom meta field to the add new term page ?> <div class="form-field"> <label for="term_meta[custom_term_meta]"><?php _e( 'Example meta field', 'pippin' ); ?></label> <input type="text" name="term_meta[custom_term_meta]" id="term_meta[custom_term_meta]" value=""> <p class="description"><?php _e( 'Enter a value for this field','pippin' ); ?></p> </div> <?php } add_action( 'category_add_form_fields', 'pippin_taxonomy_add_new_meta_field', 10, 2 );
Забележете това: {$taxonomy_name}_add_form_fields !
След като сте поставили кода би трябвало да виждате следното нещо:
За да направите така, че добавеното от вас поле да има възможността да се редактира е нужно да поставите и кода:
<?php // Edit term page function pippin_taxonomy_edit_meta_field($term) { // put the term ID into a variable $t_id = $term->term_id; // retrieve the existing value(s) for this meta field. This returns an array $term_meta = get_option( "taxonomy_$t_id" ); ?> <tr class="form-field"> <th scope="row" valign="top"><label for="term_meta[custom_term_meta]"><?php _e( 'Example meta field', 'pippin' ); ?></label></th> <td> <input type="text" name="term_meta[custom_term_meta]" id="term_meta[custom_term_meta]" value="<?php echo esc_attr( $term_meta['custom_term_meta'] ) ? esc_attr( $term_meta['custom_term_meta'] ) : ''; ?>"> <p class="description"><?php _e( 'Enter a value for this field','pippin' ); ?></p> </td> </tr> <?php } add_action( 'category_edit_form_fields', 'pippin_taxonomy_edit_meta_field', 10, 2 );
Резултата трябва да изглежда така:
Последната стъпка е да направите функцията, която ще запази вашето ново поле в базата:
// Save extra taxonomy fields callback function. function save_taxonomy_custom_meta( $term_id ) { if ( isset( $_POST['term_meta'] ) ) { $t_id = $term_id; $term_meta = get_option( "taxonomy_$t_id" ); $cat_keys = array_keys( $_POST['term_meta'] ); foreach ( $cat_keys as $key ) { if ( isset ( $_POST['term_meta'][$key] ) ) { $term_meta[$key] = $_POST['term_meta'][$key]; } } // Save the option array. update_option( "taxonomy_$t_id", $term_meta ); } } add_action( 'edited_category', 'save_taxonomy_custom_meta', 10, 2 ); add_action( 'create_category', 'save_taxonomy_custom_meta', 10, 2 );
$labels = array( 'name' => _x( 'Categories', 'taxonomy general name' ), 'singular_name' => _x( 'Category', 'taxonomy singular name' ), 'search_items' => __( 'Search Categories' ), 'all_items' => __( 'All Categories' ), 'parent_item' => __( 'Parent Category' ), 'parent_item_colon' => __( 'Parent Category:' ), 'edit_item' => __( 'Edit Category' ), 'update_item' => __( 'Update Category' ), 'add_new_item' => __( 'Add Category' ), 'new_item_name' => __( 'New Category' ), 'menu_name' => __( 'Categories' ) ); register_taxonomy('portfolio_categories',array('portfolio'), array( 'hierarchical' => true, 'labels' => $labels, 'query_var' => true, 'show_ui' => true )); add_filter('manage_edit-portfolio_categories_columns', 'add_portfolio_categories_column' );
‘hierarchical’ => true -> makes a difference between checkboxes and autosuggest
Влезте в папката на вашата тема и отворете файла functions.php.
Извикайте файла city.php.
require_once ('functions/city.php');
city.php
add_action( 'init', 'city_register'); function city_register() { $labels = array( 'name' => _x('Cities', 'post type general name'), 'singular_name' => _x('City', 'post type singular name'), 'add_new' => _x('Add New', 'City'), 'add_new_item' => __('Add New City'), 'edit_item' => __('Edit City'), 'new_item' => __('New City'), 'all_items' => __('All Cities'), 'view_item' => __('View Cities'), 'search_items' => __('Search Cities'), 'not_found' => __('No cities found'), 'not_found_in_trash' => __('No cities found in Trash'), 'parent_item_colon' => '', 'menu_name' => 'Cities' ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => true, 'capability_type' => 'post', 'hierarchical' => false, 'supports' => array('title', 'editor', 'thumbnail', 'page-attributes'), 'menu_icon' => 'dashicons-flag' ); register_post_type('city', $args); }
След като вече сте създали новия тип постове, може да го извикате в предната част на сайта по следният начин:
template-city.php
<?php $args = array( 'posts_per_page' => -1, 'orderby' => 'menu_order', 'order'=>'ASC', 'post_type' => 'city'); query_posts($args); $lastposts = get_posts( $args ); ?> <?php foreach ( $lastposts as $post ) : $post_orig = $post; setup_postdata( $post ); ?> <div class="city"> <h3><?php the_title(); ?></h3> <div class="thumb"> <?php the_post_thumbnail(array(500, 500)); ?> </div> <?php the_content(); ?> </div> <?php endforeach; ?> <?php wp_reset_postdata();?> <?php wp_reset_query();?>
Влезте във functions.php на вашата тема и първото нещо, което трябва да направите е да включите поддръжката на изображения чрез команда:
add_theme_support('post-thumbnails');
Новият вид изображения се декларират по следният начин:
add_image_size('prod-thumb', 353, 235, true); add_image_size('prod-thumb-2', 353, 353, true);
Във фронтенд-а викате създадените от системата картинки:
$thumb = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), "prod-thumb"); <img src="<?php echo $thumb[0] ?>" alt="" width="<?php echo $thumb[1] ?>" height="<?php echo $thumb[2] ?>" />
Отворете functions.php на вашата тема и поставете следния код:
$i = 1; $args = array( 'name' => "Right sidebar", 'id' => "sidebar-$i", 'description' => '', 'class' => '', 'before_widget' => '', 'after_widget' => "\n", 'before_title' => '<h2 class="widgettitle">', 'after_title' => "</h2>\n", ); register_sidebar( $args );
По този начин може да декларирате колкото ви трябват sidebars.
Визуализацията във фронтенд-а става чрез следната функция:
<?php dynamic_sidebar( 'sidebar-1' ); ?>
<form method="post" action="" enctype="multipart/form-data"> <p> <input type="file" name="myfile" id="myfile" /> </p> <p><input type="submit" value="Uploaden" id="submit" name="submit" class="submit" /></p> </form>
// https://cube3x.com/upload-files-to-wordpress-media-library-using-php/ if(@$_FILES['myfile']['size']){ if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' ); if ( ! function_exists( 'wp_generate_attachment_metadata' ) ) require_once( ABSPATH . 'wp-admin/includes/image.php' ); $uploadedfile = $_FILES['myfile']; if($uploadedfile){ $upload_overrides = array( 'test_form' => false ); $movefile = wp_handle_upload( $uploadedfile, $upload_overrides ); if ( $movefile ) { $post = array( 'post_title' => time(), 'post_content' => '', 'post_status' => 'publish', 'post_type' => 'card' ); $upload_post_id = wp_insert_post($post); do_action('wp_insert_post', 'wp_insert_post'); $wp_filetype = $movefile['type']; $filename = $movefile['file']; $wp_upload_dir = wp_upload_dir(); $attachment = array( 'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ), 'post_mime_type' => $wp_filetype, 'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment( $attachment, $filename, $upload_post_id); $attach_data = wp_generate_attachment_metadata($attach_id, $filename); //dump($attach_data); die; wp_update_attachment_metadata($attach_id, $attach_data); set_post_thumbnail( $upload_post_id, $attach_id); if($attach_id) header("Location: ".get_permalink(PAGE_ID_EXAMPLE)); } } }
Първо спираме ETag header-а тъй като ще използваме EXPIRES CACHING:
# ---------------------------------------------------------------------- # Expire Header # ---------------------------------------------------------------------- # Use UTF-8 encoding for anything served text/plain or text/html AddDefaultCharset UTF-8 # Force UTF-8 for a number of file formats AddCharset UTF-8 .atom .css .js .json .rss .vtt .xml # FileETag None is not enough for every server. Header unset ETag # Since we’re sending far-future expires, we don’t need ETags for static content. # developer.yahoo.com/performance/rules.html#etags FileETag None # Send CORS headers if browsers request them; enabled by default for images. # mod_headers, y u no match by Content-Type?! SetEnvIf Origin ":" IS_CORS Header set Access-Control-Allow-Origin "*" env=IS_CORS # Allow access to web fonts from all domains. Header set Access-Control-Allow-Origin "*" Header set X-Powered-By "WP Rocket/2.8.14" Header unset Pragma Header append Cache-Control "public" Header unset Last-Modified Header unset Pragma Header append Cache-Control "public" # Expires headers (for better cache control) ExpiresActive on # Perhaps better to whitelist expires rules? Perhaps. ExpiresDefault "access plus 1 month" # cache.appcache needs re-requests in FF 3.6 (thanks Remy ~Introducing HTML5) ExpiresByType text/cache-manifest "access plus 0 seconds" # Your document html ExpiresByType text/html "access plus 0 seconds" # Data ExpiresByType text/xml "access plus 0 seconds" ExpiresByType application/xml "access plus 0 seconds" ExpiresByType application/json "access plus 0 seconds" # Feed ExpiresByType application/rss+xml "access plus 1 hour" ExpiresByType application/atom+xml "access plus 1 hour" # Favicon (cannot be renamed) ExpiresByType image/x-icon "access plus 1 week" # Media: images, video, audio ExpiresByType image/gif "access plus 1 month" ExpiresByType image/png "access plus 1 month" ExpiresByType image/jpg "access 1 year" ExpiresByType image/jpeg "access 1 year" ExpiresByType video/ogg "access plus 1 month" ExpiresByType audio/ogg "access plus 1 month" ExpiresByType video/mp4 "access plus 1 month" ExpiresByType video/webm "access plus 1 month" # HTC files (css3pie) ExpiresByType text/x-component "access plus 1 month" # Webfonts ExpiresByType application/x-font-ttf "access plus 1 month" ExpiresByType font/opentype "access plus 1 month" ExpiresByType application/x-font-woff "access plus 1 month" ExpiresByType application/x-font-woff2 "access plus 1 month" ExpiresByType image/svg+xml "access plus 1 month" ExpiresByType application/vnd.ms-fontobject "access plus 1 month" # CSS and JavaScript ExpiresByType text/css "access plus 1 year" ExpiresByType application/javascript "access plus 1 year" # Gzip compression # Active compression SetOutputFilter DEFLATE # Force deflate for mangled headers SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding # Don’t compress images and other uncompressible content SetEnvIfNoCase Request_URI \ \.(?:gif|jpe?g|png|rar|zip|exe|flv|mov|wma|mp3|avi|swf|mp?g|mp4|webm|webp)$ no-gzip dont-vary # Compress all output labeled with one of the following MIME-types AddOutputFilterByType DEFLATE application/atom+xml \ application/javascript \ application/json \ application/rss+xml \ application/vnd.ms-fontobject \ application/x-font-ttf \ application/xhtml+xml \ application/xml \ font/opentype \ image/svg+xml \ image/x-icon \ text/css \ text/html \ text/plain \ text/x-component \ text/xml Header append Vary: Accept-Encoding # ---------------------------------------------------------------------- # Fonts # ---------------------------------------------------------------------- # Add correct content-type for fonts AddType application/vnd.ms-fontobject .eot AddType font/ttf .ttf AddType font/otf .otf AddType font/x-woff .woff AddType image/svg+xml .svg # Compress compressible fonts AddOutputFilterByType DEFLATE font/ttf font/otf image/svg+xml # Add a far future Expires header for fonts ExpiresByType application/vnd.ms-fontobject "access plus 1 year" ExpiresByType font/ttf "access plus 1 year" ExpiresByType font/otf "access plus 1 year" ExpiresByType font/x-woff "access plus 1 year" ExpiresByType image/svg+xml "access plus 1 year"
Remove Query Strings
Добавете следния код в function.php (WordPress)
function _remove_script_version( $src ){ $parts = explode( '?ver', $src ); return $parts[0]; } add_filter( 'script_loader_src', '_remove_script_version', 15, 1 ); add_filter( 'style_loader_src', '_remove_script_version', 15, 1 );
function get_cat_count_downloads_by_cat($cat_id){ global $wpdb; $total_downloads = $wpdb->get_col($wpdb->prepare ("SELECT meta_value FROM wp_postmeta as pm INNER JOIN wp_term_relationships as tr ON (pm.post_id = tr.object_id) INNER JOIN wp_term_taxonomy as tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id) WHERE 1 AND tt.term_taxonomy_id = '".$cat_id."' AND pm.meta_key = 'mp3_downloads'")); return array_sum( $total_downloads ); }