חיפוש

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

הוספת Meta Box מותאם לעורך הפוסטים בוורדפרס

הוספת meta box מותאם לעורך הפוסטים עבור שמירת נתונים נוספים ללא תוסף כמו ACF. לעוד על רישום שדות מותאמים.

add_action( 'add_meta_boxes', function () {
    add_meta_box(
        'savvy_post_subtitle',
        'Post Subtitle',
        'savvy_subtitle_metabox_html',
        'post',
        'normal',
        'high'
    );
} );

function savvy_subtitle_metabox_html( $post ) {
    $value = get_post_meta( $post->ID, '_savvy_subtitle', true );
    wp_nonce_field( 'savvy_subtitle_nonce', 'savvy_subtitle_nonce' );
    printf(
        '<input type="text" name="savvy_subtitle" value="%s" style="width:100%%;" />',
        esc_attr( $value )
    );
}

add_action( 'save_post', function ( $post_id ) {
    if ( ! isset( $_POST['savvy_subtitle_nonce'] ) ||
         ! wp_verify_nonce( $_POST['savvy_subtitle_nonce'], 'savvy_subtitle_nonce' ) ) {
        return;
    }

    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }

    if ( isset( $_POST['savvy_subtitle'] ) ) {
        update_post_meta(
            $post_id,
            '_savvy_subtitle',
            sanitize_text_field( $_POST['savvy_subtitle'] )
        );
    }
} );

הוסיפו ל-functions.php. שנו את מפתח ה-meta, הכותרת וסוג ה-input בהתאם לצרכים שלכם.

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

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

add_action( 'admin_enqueue_scripts', function ( $hook ) {
    // Only load on the post edit screen
    if ( $hook !== 'post.php' && $hook !== 'post-new.php' ) {
        return;
    }

    wp_enqueue_style(
        'savvy-admin-custom',
        get_template_directory_uri() . '/css/admin-custom.css',
        array(),
        '1.0.0'
    );

    wp_enqueue_script(
        'savvy-admin-custom',
        get_template_directory_uri() . '/js/admin-custom.js',
        array( 'jquery' ),
        '1.0.0',
        true
    );
} );

הוסיפו ל-functions.php. הפרמטר $hook מציין איזה עמוד ניהול נטען. ערכים נפוצים: post.php, edit.php, upload.php, options-general.php.

הוספת Bulk Actions מותאמים לרשימת הפוסטים בוורדפרס

הוספת אפשרות מותאמת לתפריט bulk actions ברשימת הפוסטים. בדוגמה זו מסמנים פוסטים נבחרים כ-"Featured". לעוד על הוקים בוורדפרס.

add_filter( 'bulk_actions-edit-post', function ( $actions ) {
    $actions['mark_featured'] = 'Mark as Featured';
    return $actions;
} );

add_filter( 'handle_bulk_actions-edit-post', function ( $redirect_to, $action, $post_ids ) {
    if ( $action !== 'mark_featured' ) {
        return $redirect_to;
    }

    foreach ( $post_ids as $post_id ) {
        update_post_meta( $post_id, '_is_featured', '1' );
    }

    return add_query_arg( 'marked_featured', count( $post_ids ), $redirect_to );
}, 10, 3 );

add_action( 'admin_notices', function () {
    if ( empty( $_REQUEST['marked_featured'] ) ) {
        return;
    }

    $count = intval( $_REQUEST['marked_featured'] );
    printf(
        '<div class="notice notice-success is-dismissible"><p>%d post(s) marked as featured.</p></div>',
        $count
    );
} );

הוסיפו ל-functions.php. שנו את mark_featured ואת מפתח ה-meta בהתאם לצורך שלכם.

יצירת Shortcode פשוט עם Attributes בוורדפרס

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

function savvy_button_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'url'   => '#',
        'text'  => 'Click Here',
        'color' => 'blue',
    ), $atts, 'savvy_button' );

    return sprintf(
        '<a href="%s" class="savvy-btn savvy-btn-%s">%s</a>',
        esc_url( $atts['url'] ),
        esc_attr( $atts['color'] ),
        esc_html( $atts['text'] )
    );
}

add_shortcode( 'savvy_button', 'savvy_button_shortcode' );

הוסיפו ל-functions.php. שימוש: [savvy_button url="/contact/" text="Contact Us" color="gold"].

רישום Endpoint מותאם ב-REST API של וורדפרס

רישום endpoint מותאם ב-REST API בכדי לחשוף מידע מהתבנית או מהתוסף שלכם. לעוד על אבטחת REST API.

add_action( 'rest_api_init', function () {
    register_rest_route( 'savvy/v1', '/recent-posts/', array(
        'methods'             => 'GET',
        'callback'            => 'savvy_get_recent_posts',
        'permission_callback' => '__return_true',
    ) );
} );

function savvy_get_recent_posts() {
    $posts = get_posts( array(
        'numberposts' => 5,
        'post_status' => 'publish',
    ) );

    $data = array();
    foreach ( $posts as $post ) {
        $data[] = array(
            'id'    => $post->ID,
            'title' => $post->post_title,
            'link'  => get_permalink( $post ),
        );
    }

    return rest_ensure_response( $data );
}

הוסיפו ל-functions.php. הגישה דרך /wp-json/savvy/v1/recent-posts/. הגדירו permission_callback בכדי להגביל גישה במידת הצורך.

הוספת הודעות מותאמות בממשק הניהול של וורדפרס

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

add_action( 'admin_notices', function () {
    $screen = get_current_screen();

    if ( $screen->id !== 'edit-post' ) {
        return;
    }

    echo '<div class="notice notice-warning is-dismissible">';
    echo '<p>Remember to set a featured image before publishing.</p>';
    echo '</div>';
} );

הוסיפו ל-functions.php. שנו את בדיקת $screen->id ואת הטקסט לפי הצורך. השתמשו ב-notice-success, notice-error או notice-info לסגנונות נוספים.

תזמון Cron לניקוי Transients שפג תוקפם

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

if ( ! wp_next_scheduled( 'savvy_cleanup_transients' ) ) {
    wp_schedule_event( time(), 'weekly', 'savvy_cleanup_transients' );
}

add_action( 'savvy_cleanup_transients', function () {
    global $wpdb;
    $wpdb->query(
        "DELETE a, b FROM {$wpdb->options} a
        LEFT JOIN {$wpdb->options} b
            ON b.option_name = REPLACE( a.option_name, '_transient_timeout_', '_transient_' )
        WHERE a.option_name LIKE '\_transient\_timeout\_%'
            AND a.option_value < UNIX_TIMESTAMP()"
    );
} );

הוסיפו ל-functions.php. ה-cron רץ פעם בשבוע ומסיר רק transients שפג תוקפם.

הסרת קישורי REST API מה-header

וורדפרס מוסיפה קישורי REST API (wp-json) ל-wp_head. אם אינכם צריכים גישה ציבורית ל-API, הסירו את הקישורים. הוסיפו ל-functions.php. לעוד על אבטחת REST API.

remove_action( 'wp_head', 'rest_output_link_wp_head' );
remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
remove_action( 'template_redirect', 'rest_output_link_header', 11 );

ביטול עדכונים אוטומטיים בוורדפרס

וורדפרס מעדכנת אוטומטית גרסאות מינוריות. אם אתם מעדיפים לשלוט בעדכונים ידנית, הוסיפו את הקוד ל-wp-config.php. לעוד על ביטול עדכונים אוטומטיים.

define( 'AUTOMATIC_UPDATER_DISABLED', true );
add_filter( 'auto_update_core', '__return_false' );
add_filter( 'auto_update_plugin', '__return_false' );
add_filter( 'auto_update_theme', '__return_false' );

ה-define הוסיפו ל-wp-config.php, וה-add_filter ל-functions.php.

הסרת jQuery Migrate

וורדפרס טוענת jQuery Migrate לצורך תאימות לאחור. אם האתר והתוספים שלכם תומכים ב-jQuery עדכני, ניתן להסיר את Migrate ולחסוך בקשה HTTP. הוסיפו ל-functions.php. לעוד על אופטימיזציית ביצועים.

add_action( 'wp_default_scripts', function( $scripts ) {
	if ( ! is_admin() && isset( $scripts->registered['jquery'] ) ) {
		$script = $scripts->registered['jquery'];
		if ( $script->deps ) {
			$script->deps = array_diff( $script->deps, array( 'jquery-migrate' ) );
		}
	}
} );
Savvy WordPress Development official logo