ארכיונים: Snippets | עמוד 17

פונקציה לזיהוי האם עמוד אב או עמוד כלשהו מתחתיו

ישנה פונקציה מובנית בוורדפרס המאפשרת בדיקה האם מדובר בעמוד מסויים:

if ( is_page(5) ) {
        // do some stuff
    }

או האם העמוד הוא תחת עמוד מסויים (child page):

if ( $post->post_parent == '5' ) {
        // do some stuff
    }

אך אין פונקציה מובנית בוורדפרס שבודקת שני תנאים אלו יחד, וזוהי נורא נחוצה ומצאתי לה הרבה שימושים. לדוגמא – במידה ואנו רוצים לטעון קובץ js לעמוד סרטונים ולכל עמוד שבא תחתיו…

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

function is_tree($the_page_id) {   
    // $the_page_id = The ID of the page we're looking for pages underneath
    
    global $post;         
    // load details about this page
    
    if(is_page()&&($post->post_parent==$the_page_id||is_page($the_page_id))) 
       return true;   // we're at the page or at a sub page
    else 
       return false;  // we're elsewhere
    };

שימוש

if (is_tree(5)) {
        // do some staff
    }

לעוד על תבניות עמוד בוורדפרס, תנו מבט בהיררכיה של תבניות עמוד בוורדפרס.

שינוי ברירת המחדל של פוסטים למצב פרטי

קטע הקוד הבא יאפשר לכם לקבוע כי מצב ברירת המחדל של פוסטים באתר הוורדפרס שלכם יהיה פרטי.

<?php 
/***** BEGIN HERE *****/
function default_posts_to_private()
{
	global $post;

	if ( $post->post_status == 'publish' ) {
		$visibility = 'public';
		$visibility_trans = __('Public');
	} elseif ( !empty( $post->post_password ) ) {
		$visibility = 'password';
		$visibility_trans = __('Password protected');
	} elseif ( $post->post_type == 'post' && is_sticky( $post->ID ) ) {
		$visibility = 'public';
		$visibility_trans = __('Public, Sticky');
	} else {
		$post->post_password = '';
		$visibility = 'private';
		$visibility_trans = __('Private');
	} 
?>

	<script type="text/javascript">
		(function($){
			try {
				$('#post-visibility-display').text('<?php echo $visibility_trans; ?>');
				$('#hidden-post-visibility').val('<?php echo $visibility; ?>');
				$('#visibility-radio-<?php echo $visibility; ?>').attr('checked', true);
			} catch(err){}
		}) (jQuery);
	</script>
	<?php
add_action( 'post_submitbox_misc_actions' , 'default_posts_to_private' );

קוד זה משתמש בהוק של וורדפרס. למידע נוסף בהבנת הוקים בוורדפרס.

יצירת מספר טקסונומיות בפונקציה אחת

במצבים בהם אתם עובדים על פרוייקט ונדרשים ליצור מספר טקסונומיות, נכון יהיה להשתמש בפונקציה זו מאשר ליצור פונקציה לכל טקסונומיה בנפרד. הכניסה במערך את הפרמטרים של כל טקסונומיה והפונקציה כבר תדאג לשאר…

<?php
/**
 * Register Multiple Taxonomies
 *
 */
function register_multiple_taxonomies() {
    $taxonomies = array(
        array(
            'slug'         => 'job-department',
            'single_name'  => 'Department',
            'plural_name'  => 'Departments',
            'post_type'    => 'jobs',
            'rewrite'      => array( 'slug' => 'department' ),
        ),
        array(
            'slug'         => 'job-type',
            'single_name'  => 'Type',
            'plural_name'  => 'Types',
            'post_type'    => 'jobs',
            'hierarchical' => false,
        ),
        array(
            'slug'         => 'job-experience',
            'single_name'  => 'Min-Experience',
            'plural_name'  => 'Min-Experiences',
            'post_type'    => 'jobs',
        ),
    );
    foreach( $taxonomies as $taxonomy ) {
        $labels = array(
            'name' => $taxonomy['plural_name'],
            'singular_name' => $taxonomy['single_name'],
            'search_items' =>  'Search ' . $taxonomy['plural_name'],
            'all_items' => 'All ' . $taxonomy['plural_name'],
            'parent_item' => 'Parent ' . $taxonomy['single_name'],
            'parent_item_colon' => 'Parent ' . $taxonomy['single_name'] . ':',
            'edit_item' => 'Edit ' . $taxonomy['single_name'],
            'update_item' => 'Update ' . $taxonomy['single_name'],
            'add_new_item' => 'Add New ' . $taxonomy['single_name'],
            'new_item_name' => 'New ' . $taxonomy['single_name'] . ' Name',
            'menu_name' => $taxonomy['plural_name']
        );
        
        $rewrite = isset( $taxonomy['rewrite'] ) ? $taxonomy['rewrite'] : array( 'slug' => $taxonomy['slug'] );
        $hierarchical = isset( $taxonomy['hierarchical'] ) ? $taxonomy['hierarchical'] : true;
    
        register_taxonomy( $taxonomy['slug'], $taxonomy['post_type'], array(
            'hierarchical' => $hierarchical,
            'labels' => $labels,
            'show_ui' => true,
            'query_var' => true,
            'rewrite' => $rewrite,
        ));
    }
    
}
add_action( 'init', 'register_multiple_taxonomies' );

כיצד לחלק את הפוסטים בלולאה של וורדפרס לקבוצות?

בפרוייקט האחרון שלי, נדרשתי לחלק את הלולאה של וורדפרס לקבוצות של שלושה פוסטים, כלומר במידה וישנם תשעה פוסטים כל שלושה מהם יהיו ב div שעוטף אותן. ניתן לבצע זאת על ידי שימוש ב counter ובדיקה בתוך הלולאה האם הוא כפולה של 3 ואם כן, לסגור את div. במידה ואתם מעוניינים לשנות את מספר הפוסטים בקבוצה פשוט שנו את הספרה 3 בשורה מספר 14. הנה הקוד:

<?php if ( have_posts() ) :
	$i = 0; // counter
	while ( have_posts() ) : the_post();
		if ( $i % 3 == 0 ) { // if counter is multiple of 3, put an opening div ?>
			<div>
		<?php } ?>
				<div class="single_item">
					<h2>
						<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?>
						</a>
					</h2>
				</div>
		<?php $i ++;
		if ( $i % 3 == 0 ) { // if counter is multiple of 3, put an closing div ?>
			</div>
		<?php } ?>

	<?php endwhile; ?>
	<?php
	if ( $i % 3 != 0 ) { // put closing div here if loop is not exactly a multiple of 3 ?>
		</div>
	<?php } ?>

<?php endif; ?>

לעוד התאמות ללולאה, תנו מבט בכיצד להסיר קטגוריה מהלולאה הראשית.

הוספת תוכן לתיאור המוצר בווקומרס

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

function change_woocommerce_description( $content ) {
    // Only for single product pages in woocommerce
    if ( is_product() ) {
        // The custom content to add
        $custom_content = '<p class="custom-content">' . __("This is the last line in the description", "woocommerce").'</p>';
        // Inserting the custom content at the end of the current product description
        $content .= $custom_content;
    }
    return $content;
}
add_filter( 'the_content', 'change_woocommerce_description' );

עוד מידע על שינוי והוספת שדות למוצרים של ווקומרס תמצאו בפוסט כיצד להוסיף שדות נוספים (Custom Fields) לעמוד המוצר של ווקומרס.

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

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

/**
 * Search SQL filter for matching against post title only.
 *
 * @param   string      $search
 * @param   WP_Query    $wp_query
 */
function wpse_11826_search_by_title( $search, $wp_query ) {
    if ( ! empty( $search ) && ! empty( $wp_query->query_vars['search_terms'] ) ) {
        global $wpdb;

        $q = $wp_query->query_vars;
        $n = ! empty( $q['exact'] ) ? '' : '%';

        $search = array();

        foreach ( ( array ) $q['search_terms'] as $term )
            $search[] = $wpdb->prepare( "$wpdb->posts.post_title LIKE %s", $n . $wpdb->esc_like( $term ) . $n );

        if ( ! is_user_logged_in() )
            $search[] = "$wpdb->posts.post_password = ''";

        $search = ' AND ' . implode( ' AND ', $search );
    }

    return $search;
}

add_filter( 'posts_search', 'wpse_11826_search_by_title', 10, 2 );

לעוד על שיפור החיפוש בוורדפרס, תנו מבט בRelevanssi – חיפוש טוב יותר לוורדפרס.

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

ישנם מספר דרכים להוסיף Google Fonts לאתר וורדפרס, אתן פה דוגמה לשתיים מהן. אפשרות ראשונה והפחות מומלצת היא להוסיף את הפונטים ישירות ל header.php של התבנית (כמובן שעדיף בתבנית בת).

<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Lora|Oswald" media="screen">

כשאתם משתמשים בשיטה זו שימו לב כי עליכם להוסיף את הקריאה ל Google Fonts לפני שאתם קוראים לקובץ stylesheet הראשי.

אפשרות שנייה ויותר מומלצת היא על ידי שימוש ב wp_register_style ו wp_enqueue_style. הוסיפו את הקוד הבא לקובץ functions.php:


/* The Right way to add Google Fonts to WordPress */
function add_my_google_fonts() {

	wp_register_style('my-googleFonts', 'https://fonts.googleapis.com/css?family=Open+Sans:300italic,300,600,700,400');
    wp_enqueue_style( 'my-googleFonts');
}
add_action('wp_enqueue_scripts', 'add_my_google_fonts');

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

ישנה גם אפשרות להטמעה לוקאלית של פונטים מגוגל. להטמעה לוקאלית מספר יתרונות ואם מעניין אתכם הנושא, תנו מבט בפוסט טעינה לוקאלית של פונטים מגוגל (Google Fonts).

הוספת class לפוסט האחרון בלולאה

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


// Add a class to the last post in a loop
function last_post_class($classes){
	global $wp_query;
    
	if(($wp_query->current_post+1) == $wp_query->post_count) $classes[] = 'last';
	return $classes;
    
}
    add_filter('post_class', 'last_post_class');

לעוד על מבנה התבניות בוורדפרס, תנו מבט בהיררכיה של תבניות עמוד בוורדפרס.

קביעת אורך מינימלי לתגובות בוורדפרס

אם אינכם מעוניינים בתגובות קצרות לפוסטים שלכם כגון 'תודה !' או 'מאמר נפלא…' וכו׳.. הוסיפו את הקוד הבא לקובץ functions.php, וקבעו את מספר התווים המינימלי בשורה מספר 4.


function minimal_comment_length( $commentdata ) {
    $minimalCommentLength = 20;
    if ( strlen( trim( $commentdata['comment_content'] ) ) < $minimalCommentLength ) {

        wp_die( 'התגובה חייבת להכיל ' . $minimalCommentLength . ' תווים לפחות.' );

    }

    return $commentdata;
}
add_filter( 'preprocess_comment', 'minimal_comment_length' );

לעוד על ניהול תגובות, תנו מבט בהצגת מספר התגובות הכולל.