Home / Admin / functions.php
Duplicate Snippet

Embed Snippet on Your Site

functions.php

HARUKI KAWAHATA
<10
Code Preview
php
<?php
<?php
// jQuery AJAXでお気に入りトグル
function enqueue_scripts() {
    wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'enqueue_scripts');
add_action('wp_footer', function () {
    ?>
    <script>
    jQuery(function($) {
        $(document).on('click', '.favorite-toggle', function(e) {
            e.preventDefault();
            const btn = $(this);
            const post_id = btn.data('post-id');
            const isFavorited = btn.attr('data-favorited') === '1';
            
            $.post('<?php echo admin_url('admin-ajax.php'); ?>', {
                action: 'toggle_favorite',
                post_id: post_id
            }, function(response) {
                if (response.success) {
                    btn.text(isFavorited ? '♡' : '❤️').attr('data-favorited', isFavorited ? '0' : '1');
                } else {
                    console.error('お気に入りのトグルに失敗しました。');
                }
            });
        });
    });
    </script>
    <?php
});
// カスタム投稿タイプ「listings」の登録
function register_custom_post_type() {
    register_post_type('listings', [
        'labels' => [
            'name' => 'Listings',
            'singular_name' => 'Listing'
        ],
        'public' => true,
        'has_archive' => true,
        'supports' => ['title', 'editor', 'thumbnail', 'author'],
        'rewrite' => ['slug' => 'listings']
    ]);
}
add_action('init', 'register_custom_post_type');
// お気に入りトグルボタンショートコード
add_shortcode('favorite_button', function($atts) {
    if (!is_user_logged_in()) return '';
    
    $post_id = $atts['post_id'] ?? get_the_ID();
    $user_id = get_current_user_id();
    $favorites = get_user_meta($user_id, 'favorite_listings', true);
    if (!is_array($favorites)) $favorites = [];
    $is_favorite = in_array($post_id, $favorites);
    ob_start(); ?>
    <span class="favorite-toggle" 
          data-post-id="<?php echo esc_attr($post_id); ?>" 
          data-favorited="<?php echo $is_favorite ? '1' : '0'; ?>">
        <?php echo $is_favorite ? '❤️' : '♡'; ?>
    </span>
    <?php return ob_get_clean();
});
// お気に入り追加/削除 AJAX処理
add_action('wp_ajax_toggle_favorite', function() {
    if (!is_user_logged_in()) wp_send_json_error();
    $post_id = intval($_POST['post_id']);
    $user_id = get_current_user_id();
    $favorites = get_user_meta($user_id, 'favorite_listings', true);
    if (!is_array($favorites)) $favorites = [];
    
    if (in_array($post_id, $favorites)) {
        $favorites = array_diff($favorites, [$post_id]);
    } else {
        $favorites[] = $post_id;
    }
    update_user_meta($user_id, 'favorite_listings', $favorites);
    wp_send_json_success();
});
// [my_favorite_listings_detailed] お気に入り詳細表示
add_shortcode('my_favorite_listings_detailed', function () {
    if (!is_user_logged_in()) return '<p>Please <a href="/login/">login</a> to view your favorites.</p>';
    $user_id = get_current_user_id();
    $favorites = get_user_meta($user_id, 'favorite_listings', true);
    if (!is_array($favorites) || empty($favorites)) return '<p>You have no favorite listings.</p>';
    $args = [
        'post_type' => 'listings',
        'post__in' => $favorites,
        'orderby' => 'post__in',
        'posts_per_page' => -1
    ];
    $query = new WP_Query($args);
    ob_start();
    while ($query->have_posts()) : $query->the_post();
        $post_id = get_the_ID();
        $title = get_the_title();
        $video = get_post_meta($post_id, 'video', true);
        $gallery_ids = get_post_meta($post_id, 'gallery_images', true);
        $price = get_post_meta($post_id, 'price', true);
        $area = get_post_meta($post_id, 'area', true);
        $location = get_post_meta($post_id, 'location', true);
        $station = get_post_meta($post_id, 'nearest_station', true);
        $built = get_post_meta($post_id, 'built', true);
        $available_after = get_post_meta($post_id, 'available_after', true);
        $maintenance_fee = get_post_meta($post_id, 'maintenancefee', true);
        $repair_fund = get_post_meta($post_id, 'longtermrepairreservefund', true);
        $car_parking = get_post_meta($post_id, 'car_parking', true);
        $balcony_area = get_post_meta($post_id, 'balcony_area', true);
        $comment = get_post_meta($post_id, 'comment', true);
        $thumb_url = get_the_post_thumbnail_url($post_id, 'large');
        ?>
        <div style="max-width: 1000px; margin: 40px auto; padding: 20px; background: #fff; border-radius: 10px;">
            <h1 style="font-size: 24px; margin-bottom: 15px; text-align: center;">
                <?php echo esc_html($title); ?>
                <?php echo do_shortcode('[favorite_button post_id="' . $post_id . '"]'); ?>
            </h1>
            <div class="swiper main-swiper" style="width: 100%; max-width: 1000px; margin: 0 auto; position: relative;">
                <div class="swiper-wrapper" style="height: 400px;">
                    <?php if (!empty($video)): ?>
                        <div class="swiper-slide"><iframe src="<?php echo esc_url($video); ?>" style="width:100%; height:100%; border:0;" allowfullscreen loading="lazy"></iframe></div>
                    <?php endif; ?>
                    <?php if ($thumb_url): ?>
                        <div class="swiper-slide"><img src="<?php echo esc_url($thumb_url); ?>" style="width:100%; height:100%; object-fit: cover;"></div>
                    <?php endif; ?>
                    <?php
                    if (is_array($gallery_ids)) {
                        foreach ($gallery_ids as $id) {
                            $img_url = wp_get_attachment_url($id);
                            if ($img_url) echo '<div class="swiper-slide"><img src="' . esc_url($img_url) . '" style="width:100%; height:100%; object-fit: cover;"></div>';
                        }
                    }
                    ?>
                </div>
                <div class="swiper-button-prev"></div>
                <div class="swiper-button-next"></div>
            </div>
            <div style="padding:20px; background:#f9f9f9; margin-top:20px;">
                <h2>Property Details</h2>
                <div style="display: flex; flex-wrap: wrap; gap: 20px;">
                    <ul style="width:48%; list-style:none; padding:0;">
                        <li><strong>Price:</strong> ¥<?php echo number_format((int)$price); ?></li>
                        <li><strong>Area:</strong> <?php echo esc_html($area); ?> </li>
                        <li><strong>Location:</strong> <?php echo esc_html($location); ?></li>
                        <li><strong>Nearest Station:</strong> <?php echo esc_html($station); ?></li>
                        <li><strong>Built Year:</strong> <?php echo esc_html($built); ?></li>
                    </ul>
                    <ul style="width:48%; list-style:none; padding:0;">
                        <li><strong>Available After:</strong> <?php echo esc_html($available_after); ?></li>
                        <li><strong>Maintenance Fee:</strong> ¥<?php echo number_format((int)$maintenance_fee); ?></li>
                        <li><strong>Repair Fund:</strong> ¥<?php echo number_format((int)$repair_fund); ?></li>
                        <li><strong>Car Parking:</strong> <?php echo esc_html($car_parking); ?></li>
                        <li><strong>Balcony Area:</strong> <?php echo esc_html($balcony_area); ?> </li>
                    </ul>
                </div>
                <div style="margin-top:15px;">
                    <div><strong>Comment:</strong><br><?php echo nl2br(esc_html($comment)); ?></div>
                    <div style="font-size:13px; color:#555;">Posted: <?php echo get_the_date('j M Y', $post_id); ?></div>
                </div>
            </div>
        </div>
    <?php
    endwhile;
    wp_reset_postdata();
    // Swiper CSSとJSの読み込み
    ?>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>
    <script>
        new Swiper('.main-swiper', {
            spaceBetween: 10,
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
        });
    </script>
    <style>
        .swiper-button-prev, .swiper-button-next {
            background-color: #007bff;
            border-radius: 50%;
            width: 40px; height: 40px;
            color: white; font-weight: bold;
            display: flex; align-items: center; justify-content: center;
        }
        .swiper-button-prev::after, .swiper-button-next::after {
            font-size: 18px; color: white;
        }
    </style>
    <?php
    return ob_get_clean();
});
// ログイン中メニュー切替(Buyer/Seller/Post状態で分岐)+Logout/Login単独表示
add_filter('wp_nav_menu_items', function ($items, $args) {
    if ($args->theme_location !== 'primary') return $items;
    $user = wp_get_current_user();
    $user_roles = (array) $user->roles;
    $is_logged_in = is_user_logged_in();
    $menu = '';
    if ($is_logged_in) {
        $name = $user->display_name;
        $menu .= '<li class="menu-item menu-item-has-children"><a href="#">Welcome ' . esc_html($name) . '</a><ul class="sub-menu">';
        
        if (in_array('buyer', $user_roles)) {
            $menu .= '<li><a href="/my-favorites/">My Favorite</a></li>';
            $menu .= '<li><a href="/account/">Your Account</a></li>';
        } elseif (in_array('um_seller', $user_roles)) {
            $has_post = get_posts(['post_type' => 'listings', 'author' => $user->ID, 'posts_per_page' => 1]);
            if ($has_post) {
                $menu .= '<li><a href="/my-post/">My Posting</a></li>';
            } else {
                $menu .= '<li><a href="/property-listing-form/">Posting</a></li>';
            }
            $menu .= '<li><a href="/account/">Your Account</a></li>';
        }
        $menu .= '</ul></li>';
        $menu .= '<li><a href="' . esc_url(wp_logout_url(home_url())) . '">Logout</a></li>';
    } else {
        $menu .= '<li><a href="/login/">Login</a></li>';
    }
    return $items . $menu;
}, 10, 2);
// フロントにCSS追加(♡と❤️の大きさ・挙動を完全固定)
add_action('wp_head', function () {
    echo '<style>
        .favorite-toggle {
            font-size: 48px !important;
            line-height: 1 !important;
            cursor: pointer;
            user-select: none;
            color: inherit !important;
            text-shadow: none !important;
            filter: none !important;
            opacity: 1 !important;
            transform: none !important;
            transition: none !important;
        }
        .favorite-toggle:hover {
            font-size: 48px !important;
            color: inherit !important;
            text-shadow: none !important;
            filter: none !important;
            opacity: 1 !important;
            transform: none !important;
            transition: none !important;
        }
    </style>';
});
// 不要な絵文字フィルターを削除
remove_filter('the_content', 'wp_staticize_emoji');
remove_filter('the_excerpt', 'wp_staticize_emoji');
remove_filter('widget_text_content', 'wp_staticize_emoji');
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('wp_print_styles', 'print_emoji_styles');
remove_action('admin_print_styles', 'print_emoji_styles');
remove_filter('wp_mail', 'wp_staticize_emoji_for_email');

Comments

Add a Comment