Search

ארכיונים: סניפטים וקטעי קוד | עמוד 6

כיצד למנוע מוורדפרס לנחש כתובות URL

הוספת הקוד הבא ל functions.php של התבנית שלכם, ימנע מוורדפרס לבצע הפנייה אוטומטית של URL לא נכון לעמוד או פוסט בעל כתובת URL דומה.

/** stop guessing urls */

function sv_no_redirect_404($redirect_url) {
    if (is_404()) {
        return false;
    }
    return $redirect_url;
}

add_filter('redirect_canonical', 'sv_no_redirect_404');

You might find more information by search google for "Stop wordpress from guessing url's".

שינוי כתובת החיפוש של וורדפרס

כברירת מחדל וורדפרס משתמשת בפרמטר "s" כ Query String על מנת לבצע חיפוש באתר. במקרים מסויימים תרצו לשנות פרמטר זה למחרוזת שונה. ניתן לעשות זאת בקלות על ידי הפונקציה הבאה:

function change_search_url_rewrite() {
    if ( is_search() && ! empty( $_GET['s'] ) ) {
        wp_redirect( home_url( "/search/" ) . urlencode( get_query_var( 's' ) ) );
        exit();
    }
}
add_action( 'template_redirect', 'change_search_url_rewrite' );

לאחר הוספת פונקציה זו, כתובת החיפוש תהיה serach/test במקום ?s=test

הצגת קטגוריות המוצרים בפירורי הלחם של ווקומרס

בכדי להציג את קטגוריית המוצר בפירורי הלחם של ווקומרס יש להוסיף את הקוד הבא לקובץ functions.php של תבנית הבת שלכם:

/**
 * Show product categories in WooCommerce breadcrumbs
 */
// Get breadcrumbs on product pages that read: Home > Shop > Product category > Product Name
add_filter( 'woo_breadcrumbs_trail', 'woo_custom_breadcrumbs_trail_add_product_categories', 20 );

function woo_custom_breadcrumbs_trail_add_product_categories ( $trail ) {
  if ( ( get_post_type() == 'product' ) && is_singular() ) {
		global $post;

		$taxonomy = 'product_cat';

		$terms = get_the_terms( $post->ID, $taxonomy );
		$links = array();

		if ( $terms && ! is_wp_error( $terms ) ) {
		$count = 0;
			foreach ( $terms as $c ) {
				$count++;
				if ( $count > 1 ) { continue; }
				$parents = woo_get_term_parents( $c->term_id, $taxonomy, true, ', ', $c->name, array() );

				if ( $parents != '' && ! is_wp_error( $parents ) ) {
					$parents_arr = explode( ', ', $parents );

					foreach ( $parents_arr as $p ) {
						if ( $p != '' ) { $links[] = $p; }
					}
				}
			}

			// Add the trail back on to the end.
			// $links[] = $trail['trail_end'];
			$trail_end = get_the_title($post->ID);

			// Add the new links, and the original trail's end, back into the trail.
			array_splice( $trail, 2, count( $trail ) - 1, $links );

			$trail['trail_end'] = $trail_end;
		}
	}

	return $trail;
}

/**
 * Retrieve term parents with separator.
 *
 * @param int $id Term ID.
 * @param string $taxonomy.
 * @param bool $link Optional, default is false. Whether to format with link.
 * @param string $separator Optional, default is '/'. How to separate terms.
 * @param bool $nicename Optional, default is false. Whether to use nice name for display.
 * @param array $visited Optional. Already linked to terms to prevent duplicates.
 * @return string
 */

if ( ! function_exists( 'woo_get_term_parents' ) ) {
function woo_get_term_parents( $id, $taxonomy, $link = false, $separator = '/', $nicename = false, $visited = array() ) {
	$chain = '';
	$parent = &get_term( $id, $taxonomy );
	if ( is_wp_error( $parent ) )
		return $parent;

	if ( $nicename ) {
		$name = $parent->slug;
	} else {
		$name = $parent->name;
	}

	if ( $parent->parent && ( $parent->parent != $parent->term_id ) && !in_array( $parent->parent, $visited ) ) {
		$visited[] = $parent->parent;
		$chain .= woo_get_term_parents( $parent->parent, $taxonomy, $link, $separator, $nicename, $visited );
	}

	if ( $link ) {
		$chain .= '<a href="' . get_term_link( $parent, $taxonomy ) . '" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $parent->name ) ) . '">'.$parent->name.'</a>' . $separator;
	} else {
		$chain .= $name.$separator;
	}
	return $chain;
	}
}

הצגת קישור לחשבון המשתמש בתבניות עמוד

הקוד הבא יציג את הקישור לעמוד ״החשבון שלי״ באתרי ווקומרס. אם המשתמש אינו מחובר יוצג עבורו הקישור עם הטקסט ״הרשם / התחבר״, אחרת יוצג הקישור עם הטקסט ״החשבון שלי״.

<?php if ( is_user_logged_in() ) { ?>
 	<a href="<?php echo get_permalink( get_option('woocommerce_myaccount_page_id') ); ?>" title="<?php _e('My Account','woothemes'); ?>"><?php _e('My Account','woothemes'); ?></a>
 <?php } 
 else { ?>
 	<a href="<?php echo get_permalink( get_option('woocommerce_myaccount_page_id') ); ?>" title="<?php _e('Login / Register','woothemes'); ?>"><?php _e('Login / Register','woothemes'); ?></a>
 <?php } ?>

עוד מידע על עמוד החשבון שלי בפוסט משחקים עם עמוד ״החשבון שלי״ בווקומרס.

לולאה בסיסית של מוצרי ווקומרס

זוהי דוגמה פשוטה ללולאה בסיסית של מוצרי ווקומרס (WooCommerce Products Loop). אם אתם מעוניינים לדעת עוד אז הנה פוסט על הדרך הנכונה לשלוף מוצרים של ווקומרס בתבנית שלכם.

<ul class="products">
	<?php
		$args = array(
			'post_type' => 'product',
			'posts_per_page' => 12
			);
		$loop = new WP_Query( $args );
		if ( $loop->have_posts() ) {
			while ( $loop->have_posts() ) : $loop->the_post();
				wc_get_template_part( 'content', 'product' );
			endwhile;
		} else {
			echo __( 'No products found' );
		}
		wp_reset_postdata();
	?>
</ul><!--/.products-->

שינוי ומודיפיקציה לפירורי הלחם של ווקומרס

נתאר מספר דוגמאות המאפשרות לשנות את פירורי הלחם (BreadCrumbs) של ווקומרס. את הסניפטים שתמצאו בפוסט זה יש להוסיף לקובץ functions.php בתבנית הבת שלכם.

שימו לב כי חלק מהסניפטים המופיעים בפוסט זה אינם יעבדו עם התבנית Storefront.

א. שינוי הטקטס "Home״

/**
 * Rename "home" in breadcrumb
 */
add_filter( 'woocommerce_breadcrumb_defaults', 'wcc_change_breadcrumb_home_text' );
function wcc_change_breadcrumb_home_text( $defaults ) {
    // Change the breadcrumb home text from 'Home' to 'Apartment'
	$defaults['home'] = 'Apartment';
	return $defaults;
}

ב. שינוי הקו המפריד (separator)

/**
 * Change the breadcrumb separator
 */
add_filter( 'woocommerce_breadcrumb_defaults', 'wcc_change_breadcrumb_delimiter' );
function wcc_change_breadcrumb_delimiter( $defaults ) {
	// Change the breadcrumb delimeter from '/' to '>'
	$defaults['delimiter'] = ' > ';
	return $defaults;
}

ג. שינוי מספר פרמטרים דיפולטיבים במקביל

/**
 * Change several of the breadcrumb defaults
 */
add_filter( 'woocommerce_breadcrumb_defaults', 'jk_woocommerce_breadcrumbs' );
function jk_woocommerce_breadcrumbs() {
    return array(
            'delimiter'   => ' &#47; ',
            'wrap_before' => '<nav class="woocommerce-breadcrumb" itemprop="breadcrumb">',
            'wrap_after'  => '</nav>',
            'before'      => '',
            'after'       => '',
            'home'        => _x( 'Home', 'breadcrumb', 'woocommerce' ),
        );
}

ד. שינוי הקישור של ״עמוד הבית״ (Home Link)

/**
 * Replace the home link URL
 */
add_filter( 'woocommerce_breadcrumb_home_url', 'woo_custom_breadrumb_home_url' );
function woo_custom_breadrumb_home_url() {
    return 'http://woocommerce.com';
}

ה. הסרה מוחלטת של פירורי הלחם

נחוץ במידה ואתם מוסיפים פירורי לחם בצורה אחרת באתר שלכם….

/**
 * Remove the breadcrumbs 
 */
add_action( 'init', 'woo_remove_wc_breadcrumbs' );
function woo_remove_wc_breadcrumbs() {
    remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20, 0 );
}

ניתן גם להסיר את פירורי הלחם של ווקומרס בעמודים מסויימים בלבד.

הסרת תוכן כלשהו של מוצר בקטגוריה מסויימת

הקוד הבא למשל יסיר את התמונות של המוצרים בעמוד מוצר יחיד של ווקומרס אך ורק עבור מוצרים תחת הקטגוריה "Cookware". ניתן כמובן להסיר כל תוכן שתרצו על ידי שימוש בהוקים של ווקומרס הקיימים לרשותכם.

/**
 * Remove product content based on category
 */
function remove_product_content() {
	// If a product in the 'Cookware' category is being viewed...
	if ( is_product() && has_term( 'Cookware', 'product_cat' ) ) {
		//... Remove the images
		remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20 );
		// For a full list of what can be removed please see woocommerce-hooks.php
	}
}
add_action( 'wp', 'remove_product_content' );

אפשרות למיון מוצרים רנדומלי בעמוד הקטלוג של ווקומרס

הקוד הבא הוא דוגמה המתארת כיצד להוסיף אפשרות של מיון (sorting) אקראי בעמוד הקטלוג של מוצרי ווקומרס. באותו אופן אתם יכולים להוסיף כל אפשרות מיון שתרצו בהתאם לאפשרויות העומדות בפניכם עבור הפרמטר orderby של WP_Query. תנו מבט ב WordPress Codex לעוד מידע על הפרמטר orderby.

על קוד זה להיות בקובץ functions.php כמובן:

/**
 * Add custom sorting options (asc/desc)
 */
add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args' );
function custom_woocommerce_get_catalog_ordering_args( $args ) {
  $orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
	if ( 'random_list' == $orderby_value ) {
		$args['orderby'] = 'rand';
		$args['order'] = '';
		$args['meta_key'] = '';
	}
	return $args;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby' );
function custom_woocommerce_catalog_orderby( $sortby ) {
	$sortby['random_list'] = 'Random';
	return $sortby;
}

כיצד לאפשר HTML במונחים (Terms) של קטגוריות ותגיות

כברירת מחדל וורדפרס מסירה HTML מהתיאור (description) של תגיות וקטגוריות. הוסיפו קוד זה לקובץ functions.php בכדי לאפשר HTML בתיאור של מונחים אלו.

/**
 * Allow HTML in term (category, tag) descriptions
 */
foreach ( array( 'pre_term_description' ) as $filter ) {
	remove_filter( $filter, 'wp_filter_kses' );
	if ( ! current_user_can( 'unfiltered_html' ) ) {
		add_filter( $filter, 'wp_filter_post_kses' );
	}
}
 
foreach ( array( 'term_description' ) as $filter ) {
	remove_filter( $filter, 'wp_kses_data' );
}

הוספת קוד מעקב משלכם בעמוד ״תודה״ של ווקומרס

הקוד שלפניכם מאפשר להוסיף קוד מעקב כלשהו בעמוד התודה (Thank You Page) של ווקומרס לאחר רכישה. המשתנה $order יכיל את כל המידע הרלוונטי של אותה הזמנה שבוצעה כך שתוכלו לשלוח את הפרטים לאותו שירות בו אתם משתמש למעקב.

שימו לב להסברים המופיעים בקוד בכדי להבין היכן להוסיף את קוד המעקב וכיצד להשתמש במשתנה זה:

/**
 * Add custom tracking code to the thank-you page
 */

function my_custom_tracking( $order_id ) {

	// Lets grab the order
	$order = wc_get_order( $order_id );

	/**
	 * Put your tracking code here
	 * You can get the order total etc e.g. $order->get_total();
	 */
	 
	// This is the order total
	$order->get_total();
 
	// This is how to grab line items from the order 
	$line_items = $order->get_items();

	// This loops over line items
	foreach ( $line_items as $item ) {
  		// This will be a product
  		$product = $order->get_product_from_item( $item );
  
  		// This is the products SKU
		$sku = $product->get_sku();
		
		// This is the qty purchased
		$qty = $item['qty'];
		
		// Line item total cost including taxes and rounded
		$total = $order->get_line_total( $item, true, true );
		
		// Line item subtotal (before discounts)
		$subtotal = $order->get_line_subtotal( $item, true, true );
	}
}
add_action( 'woocommerce_thankyou', 'my_custom_tracking' );