• プラグイン一覧
    - WCEX Item Combo Set
    - WCEX Amazon Pay
    - WCEX Wishlist お気に入りリスト
  • リリース情報
  • お役立ちコラム
  • お問い合わせ
  • サポート
    • よくある質問
      • WCEX Amazon Pay
      • WCEX Wishlist お気に入りリスト
      • wcex-item-combo-set
    • リファレンス
      • WCEX Amazon Pay
      • WCEX Wishlist お気に入りリスト
      • wcex-item-combo-set
新規会員登録
ログイン
新規会員登録
ログイン
カート
  • プラグイン一覧
    • - WCEX Item Combo Set
    • - WCEX Amazon Pay
    • - WCEX Wishlist お気に入りリスト
  • リリース情報
  • お役立ちコラム
  • サポート
    • - よくある質問
      • - WCEX Amazon Pay
      • - WCEX Wishlist お気に入りリスト
      • - wcex-item-combo-set
    • - リファレンス
      • - WCEX Amazon Pay
      • - WCEX Wishlist お気に入りリスト
      • - wcex-item-combo-set
  • お問い合わせ
Aivec APPs > WCEX Wishlist お気に入りリスト > クラス > CRUD
レファレンス
バージョン
3.1.6
絞り込み:
目的から探す
お気に入りデータを取得 お気に入りページのHTMLを取得 スナックバーアラート

目次

  • ソース
  • 関数

フック

  • アクション
  • フィルター

ファンクション

  • データ取得
  • ユーティリティー
  • 条件判断
  • 表示系

クラス

CRUD

CRUD operations (create, read, update, delete)

ソース #ソース

ファイル: src/API/CRUD.php

class CRUD
{
    /**
     * Returns member ID for the current user
     *
     * @author Evan D Shaw <evandanielshaw@gmail.com>
     * @return int
     */
    public static function getMemberId() {
        return isset($_SESSION['usces_member']['ID']) ? (int)$_SESSION['usces_member']['ID'] : 0;
    }

    /**
     * Deletes a wishlist item by ID
     *
     * @author Evan D Shaw <evandanielshaw@gmail.com>
     * @global \wpdb $wpdb
     * @param int $id
     * @return bool
     */
    public static function executeDeletion($id) {
        global $wpdb;

        if (empty(self::getMemberId())) {
            return false;
        }

        $res = $wpdb->delete(
            Master::getWishlistTableName(),
            [
                'id' => (int)$id,
                'mem_id' => self::getMemberId(),
            ],
            ['%d', '%d']
        );
        if ($res === false) {
            return false;
        }

        return true;
    }

    /**
     * Inserts item into wishlist table
     *
     * If the user is not logged in or a DB error occurs, `false` is returned,
     * otherwise `true` is returned.
     *
     * @author Evan D Shaw <evandanielshaw@gmail.com>
     * @global \wpdb $wpdb
     * @param int    $post_id
     * @param string $sku
     * @param string $serial
     * @param string $advance
     * @return bool
     */
    public static function executeAddToWishlist($post_id, $sku, $serial, $advance = '') {
        global $wpdb;

        if (empty(self::getMemberId())) {
            return false;
        }

        $srow = self::getWishlistItemBySerial($serial);
        if (!empty($srow)) {
            // return `true` if the item already exists in wishlist
            return true;
        }

        $unit_price = null;
        $tempcart = new \usces_cart();

        /*
         * `get_realprice` uses `$this->serial` internally so we need to set `serial`
         * before calling it.
         *
         * We can't use `$usces->cart->get_realprice(...)` because spoofing `serial`
         * would directly affect the cart session.
         */
        $tempcart->serial = $serial;

        // `$sku` is automatically urldecoded in `get_realprice`
        $price = (int)$tempcart->get_realprice($post_id, $sku, 1, null, $unit_price);
        $res = $wpdb->insert(
            Master::getWishlistTableName(),
            [
                'mem_id' => self::getMemberId(),
                'quantity' => 1,
                'price' => $price,
                'advance' => $advance,
                'item_serial' => $serial,
            ],
            [
                '%d',
                '%d',
                '%d',
                '%s',
                '%s',
            ]
        );

        if ($res === false) {
            return false;
        }

        return true;
    }

    /**
     * Returns the post ID of a wishlist item
     *
     * @author Evan D Shaw <evandanielshaw@gmail.com>
     * @global \wpdb $wpdb
     * @param int $id
     * @return null|int post ID if found, otherwise `null`
     */
    public static function getPostIdByWishlistItemId($id) {
        global $wpdb;

        $table = Master::getWishlistTableName();
        $serial = $wpdb->get_var($wpdb->prepare("SELECT item_serial FROM {$table} WHERE id = %d", $id));
        if ($serial === null) {
            return null;
        }

        $data = unserialize($serial);
        if (empty($data)) {
            return null;
        }

        $ids = array_keys((array)$data);
        $post_id = isset($ids[0]) ? (int)$ids[0] : null;
        if (empty($post_id)) {
            return null;
        }

        return $post_id;
    }

    /**
     * Returns a wishlist item by ID
     *
     * @author Evan D Shaw <evandanielshaw@gmail.com>
     * @global \wpdb $wpdb
     * @global null|int $usces_gp
     * @param int $id
     * @return array
     */
    public static function getWishlistItemById($id) {
        global $wpdb, $usces_gp;

        if (empty(self::getMemberId())) {
            return [];
        }

        $table = Master::getWishlistTableName();
        $res = $wpdb->get_row(
            $wpdb->prepare("SELECT * FROM {$table} WHERE mem_id = %d AND id = %d", self::getMemberId(), $id),
            ARRAY_A
        );

        if ($res === null) {
            return [];
        }

        $usces_gp = 0;
        $row = self::buildWishlistRow($res);
        if ($row['isgptekiyo'] === true) {
            $usces_gp = 1;
        }

        return $row;
    }

    /**
     * Returns a wishlist item by serial
     *
     * @author Evan D Shaw <evandanielshaw@gmail.com>
     * @global \wpdb $wpdb
     * @global null|int $usces_gp
     * @param string $serial
     * @return array See \Aivec\Welcart\Extensions\API\CRUD::buildWishlistRow()
     */
    public static function getWishlistItemBySerial($serial) {
        global $wpdb, $usces_gp;

        if (empty(self::getMemberId())) {
            return [];
        }

        $table = Master::getWishlistTableName();
        $res = $wpdb->get_row(
            $wpdb->prepare("SELECT * FROM {$table} WHERE mem_id = %d AND item_serial = %s", self::getMemberId(), $serial),
            ARRAY_A
        );

        if ($res === null) {
            return [];
        }

        $usces_gp = 0;
        $row = self::buildWishlistRow($res);
        if ($row['isgptekiyo'] === true) {
            $usces_gp = 1;
        }

        return $row;
    }

    /**
     * Returns number of items in the wishlist of a given user
     *
     * If calling from a theme file, use wcexwl_api_get_wishlist_item_count() instead.
     *
     * @important
     * @author Evan D Shaw <evandanielshaw@gmail.com>
     * @global \wpdb $wpdb
     * @return int
     */
    public static function getWishlistItemCount() {
        global $wpdb;

        if (empty(self::getMemberId())) {
            return 0;
        }

        $table = Master::getWishlistTableName();
        return (int)$wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$table} WHERE mem_id = %d",
            self::getMemberId()
        ));
    }

    /**
     * Returns wishlist rows for a given member
     *
     * If calling from a theme file, use wcexwl_api_get_and_build_wishlist_items() instead.
     *
     * @important
     * @author Evan D Shaw <evandanielshaw@gmail.com>
     * @global \wpdb $wpdb
     * @global null|int $usces_gp
     * @return array See \Aivec\Welcart\Extensions\Wishlist\API\CRUD::buildWishlistRow()
     */
    public static function getAndBuildWishlistItems() {
        global $usces_gp;

        if (empty(self::getMemberId())) {
            return [];
        }

        $usces_gp = 0;
        $rows = [];
        $rawrows = self::getWishlistItems();
        foreach ($rawrows as $item) {
            $row = self::buildWishlistRow($item);
            if ($row['isgptekiyo'] === true) {
                $usces_gp = 1;
            }

            $rows[] = $row;
        }

        return $rows;
    }

    /**
     * Returns raw wishlist rows for a given member
     *
     * If calling from a theme file, use wcexwl_api_get_wishlist_items() instead.
     *
     * @important
     * @author Evan D Shaw <evandanielshaw@gmail.com>
     * @global \wpdb $wpdb
     * @return array {
     *     Wishlist DB row contents.
     *
     *     @type int $id         Wishlist item Primary Key ID
     *     @type int $mem_id     Welcart member ID
     *     @type int $quantity   Quantity of the item. With the current implementation, this value is always `1`
     *     @type int $price      The price of the item **at the time it was added**
     *     @type string $advance Optional custom form data sent from the item page
     *     @type string $serial  The item in serialized form.
     * }
     */
    public static function getWishlistItems() {
        global $wpdb;

        if (empty(self::getMemberId())) {
            return [];
        }

        $table = Master::getWishlistTableName();
        $rows = $wpdb->get_results(
            $wpdb->prepare("SELECT * FROM {$table} WHERE mem_id = %d", self::getMemberId()),
            ARRAY_A
        );

        return !empty($rows) ? $rows : [];
    }

    /**
     * Adds meta data to a given wishlist row and returns it
     *
     * @important
     * @author Evan D Shaw <evandanielshaw@gmail.com>
     * @global \usc_e_shop $usces
     * @global \wpdb $wpdb
     * @param array $item See \Aivec\Welcart\Extensions\Wishlist\API\CRUD::getWishlistItems()
     * @return array {
     *     A key-value map of all data for the wishlist row item
     *
     *     @type int    $id                   Primary key ID of the wishlist item
     *     @type string $serial               Serialized item data. Same form as Welcart cart item serials
     *     @type int    $postId               Item post ID
     *     @type string $sku                  Item SKU
     *     @type int    $price                The **current** price of the item
     *     @type int    $quantity             The quantity of items. Unless customized, this value will always be 1
     *     @type string $advance              Custom data for the item
     *     @type array  $options              Indexed array of item options
     *     @type array  $optstrs              Array of item option strings in the form `key:value`
     *     @type array  $optmap               Key-value item option array
     *     @type bool   $itemDeleted          `true` if the item was deleted, `false` otherwise
     *     @type string $itemPermalink        URL to the item page
     *     @type string $cartThumbnailSrc     Item thumbnail source URL
     *     @type bool   $isgptekiyo           `true` if business pack is applied for the item, `false` otherwise
     *     @type bool   $inCart               `true` if the item is already in the cart, `false` otherwise
     *     @type string $itemCode             Welcart item code
     *     @type string $itemName             Welcart item name
     *     @type string $cartItemName         Item name formatted for display on the cart/wishlist page
     *     @type array  $cartItemNameParts    An array of each part of the formatted item name
     *     @type string $itemRestriction      Welcart item restriction, if applied
     *     @type string $formattedPrice       Localized price for displaying to the user
     *     @type bool   $inStock              `true` if the item is in stock, `false` otherwise
     *     @type int    $skuZaikonum          Welcart zaiko num
     *     @type int    $stockid              Welcart stock ID
     *     @type string $stock                Welcart stock display text (ie: 'In Stock')
     *     @type bool   $optionsAreValid      `true` if item options are valid, `false` otherwise
     *     @type string $cartButtonClass      CSS class for the 'Add To Cart' button
     *     @type string $cartButtonText       Text for the 'Add To Cart' button
     *     @type string $icon                 Name of the icon to display. For a full list of available icons,
     *                                        see {@link https://fomantic-ui.com/elements/icon.html}
     *     @type string $deleteButtonClass    CSS class for the delete button
     *     @type string $unitPriceLabel       Text for the unit price label
     *     @type string $stockStatusLabel     Text for the stock status label
     *     @type string $toItemPageButtonText Text for the 'To Item Page' button
     *     @type string $deleteButtonText     Text for the delete button
     *     @type string $changedOptsText      Text to display when the options for the item need to be re-selected
     *     @type string $deletedInfoText      Text to display when the item has been deleted
     * }
     */
    public static function buildWishlistRow(array $item) {
        global $usces, $wpdb;

        $row = [];
        $array = unserialize($item['item_serial']);
        $ids = array_keys($array);
        $skus = array_keys($array[$ids[0]]);
        $row['id'] = isset($item['id']) ? (int)$item['id'] : 0;
        $row['serial'] = $item['item_serial'];
        $row['postId'] = (int)$ids[0];
        $row['sku'] = $skus[0];
        $priceWhenAdded = $item['price'];

        $post_id = (int)$row['postId'];
        $sku = $row['sku'];
        $unit_price = null;
        $tempcart = new \usces_cart();

        /*
         * `get_realprice` uses `$this->serial` internally so we need to set `serial`
         * before calling it.
         *
         * We can't use `$usces->cart->get_realprice(...)` because spoofing `serial`
         * would directly affect the cart session.
         */
        $tempcart->serial = $item['item_serial'];

        // `$sku` is automatically urldecoded in `get_realprice`
        $row['price'] = (int)$tempcart->get_realprice($post_id, $sku, 1, null, $unit_price);

        $row['quantity'] = isset($item['quantity']) && (int)$item['quantity'] > 0 ? (int)$item['quantity'] : 1;
        $row['advance'] = isset($item['advance']) ? $item['advance'] : '';
        $options = $array[$ids[0]][$skus[0]];
        $opt_fields = usces_get_opts($post_id, 'sort');
        $new_opt = [];
        foreach ($opt_fields as $key => $field) {
            $name = urlencode($field['name']);
            $new_opt[$name] = isset($options[$name]) ? $options[$name] : '';
        }
        /**
         * Filters the item options array
         *
         * @param array  $options
         * @param int    $post_id Item post ID
         * @param string $sku
         * @param string $serial Serialized Welcart item
         */
        $row['options'] = apply_filters(
            'wcexwl_filter_key_unserialize_options',
            $new_opt,
            (int)$ids[0],
            $skus[0],
            $item['item_serial']
        );
        $optstrs = [];
        $optmap = [];
        if (is_array($options) && count($options) > 0) {
            foreach ($options as $key => $value) {
                $optstr = '';
                if (!empty($key)) {
                    $key = urldecode($key);
                    if (is_array($value)) {
                        $c = '';
                        $optstr = esc_html($key) . ' : ';
                        $optval = '';
                        foreach ($value as $v) {
                            $optval .= $c . nl2br(esc_html(urldecode($v)));
                            $c = ', ';
                        }
                        $optstr .= $optval;
                        $optmap[esc_html($key)] = $optval;
                    } else {
                        $optstr = esc_html($key) . ' : ' . nl2br(esc_html(urldecode($value)));
                        $optmap[esc_html($key)] = nl2br(esc_html(urldecode($value)));
                    }
                }
                if (!empty($optstr)) {
                    $optstrs[] = $optstr;
                }
            }
        }
        $row['optstrs'] = $optstrs;
        $row['optmap'] = $optmap;
        $row['itemDeleted'] = false;
        $p = get_post($post_id);
        if ($p === null) {
            $row['itemDeleted'] = true;
            $row['price'] = $priceWhenAdded;
        } else {
            $pstatus = $wpdb->get_var($wpdb->prepare("SELECT post_status FROM {$wpdb->posts} WHERE ID = %d", $post_id));
            if ($pstatus === 'trash') {
                $row['itemDeleted'] = true;
            }
        }
        $sku_code = esc_attr(urldecode($sku));
        $itemCode = $usces->getItemCode($post_id);
        $itemName = $usces->getItemName($post_id);
        $cartItemName = $usces->getCartItemName($post_id, $sku_code);
        $itemRestriction = $usces->getItemRestriction($post_id);
        $formattedPrice = usces_crform($row['price'], true, false, 'return');
        $inStock = $usces->is_item_zaiko($post_id, $sku_code);
        $skuZaikonum = $usces->getItemZaikonum($post_id, $sku_code);
        $stockid = (int)$usces->getItemZaikoStatusId($post_id, $sku_code);
        $stock = $usces->getItemZaiko($post_id, $sku_code);
        $pictid = (int)$usces->get_mainpictid($itemCode);
        $cart_thumbnail_src = wp_get_attachment_image_src($pictid, 'thumbnail', true);
        $cart_thumbnail_src = $cart_thumbnail_src[0];
        $row['itemPermalink'] = get_permalink($post_id);
        $row['cartThumbnailSrc'] = $cart_thumbnail_src;
        $row['isgptekiyo'] = usces_is_gptekiyo($post_id, $sku_code, $row['quantity']);
        $row['inCart'] = isset($_SESSION['usces_cart'][$item['item_serial']]) ? true : false;
        $row['itemCode'] = $itemCode;
        $row['itemName'] = $itemName;
        /**
         * Filters the cart item name
         *
         * @ignore
         * @param string $cart_item_name
         * @param array  $vars
         */
        $row['cartItemName'] = apply_filters(
            'usces_filter_cart_item_name',
            esc_html($cartItemName),
            [
                'post_id' => $post_id,
                'sku' => $sku,
            ]
        );
        $row['cartItemNameParts'] = explode('<br />', $row['cartItemName']);
        $row['itemRestriction'] = $itemRestriction;
        $row['formattedPrice'] = $formattedPrice;
        $row['inStock'] = $inStock;
        $row['skuZaikonum'] = $skuZaikonum;
        $row['stockid'] = $stockid;
        $row['stock'] = $stock;
        $row['optionsAreValid'] = Validation::optionsAreValid($post_id, is_array($options) ? $options : []);

        /*
         * The following properties are for HTML and CSS. In general, it's bad practice to mix raw data with
         * display data. But for our case, we use WordPress PHP hooks to allow for customization of these values
         * AND we update HTML and CSS with JavaScript so it makes the most sense to set the values in one place.
         */
        $display = Master::getFilterableValues();
        $btnprimary = $display['btnprimary'];
        $cartButtonClass = "ui wcexwl add-to-cart-btn ${btnprimary} tiny fluid button";
        $cartButtonText = __('To Cart', 'wcexwl');
        $icon = 'cart';
        if ($row['inCart']) {
            $cartButtonClass = "ui wcexwl add-to-cart-btn ${btnprimary} tiny fluid basic disabled button";
            $cartButtonText = __('Added to Cart', 'wcexwl');
            $icon = 'check';
        }
        /**
         * Filters the 'Add to Cart' or 'Added to Cart' button CSS class on the wishlist page
         *
         * @important
         * @param string $cartButtonClass
         * @param array  $row Array of row contents already added
         */
        $row['cartButtonClass'] = apply_filters('wcexwl_filter_wlpage_cart_btn_class', $cartButtonClass, $row);
        /**
         * Filters the 'Add to Cart' or 'Added to Cart' button text on the wishlist page
         *
         * @important
         * @param string $cartButtonText
         * @param array  $row Array of row contents already added
         */
        $row['cartButtonText'] = apply_filters('wcexwl_filter_wlpage_cart_btn_text', $cartButtonText, $row);
        /**
         * Filters the 'Add to Cart' or 'Added to Cart' button icon on the wishlist page
         *
         * @important
         * @param string $icon
         * @param array  $row Array of row contents already added
         */
        $row['icon'] = apply_filters('wcexwl_filter_wlpage_tocart_btn_icon', $icon, $row);
        /**
         * Filters the 'Delete' button CSS class on the wishlist page
         *
         * @important
         * @param string $class
         * @param array  $row Array of row contents already added
         */
        $row['deleteButtonClass'] = apply_filters('wcexwl_filter_wlpage_delete_btn_class', 'ui tiny fluid button', $row);
        /**
         * Filters the 'Unit price' label text for an item on the wishlist page
         *
         * @important
         * @param string $text
         * @param array  $row Array of row contents already added
         */
        $row['unitPriceLabel'] = apply_filters('wcexwl_filter_wlpage_unit_price_label', __('Unit price', 'wcexwl'), $row);
        /**
         * Filters the 'Stock status' label text for an item on the wishlist page
         *
         * @important
         * @param string $text
         * @param array  $row Array of row contents already added
         */
        $row['stockStatusLabel'] = apply_filters('wcexwl_filter_wlpage_stock_status_label', __('stock status', 'wcexwl'), $row);
        /**
         * Filters the 'To Item Page' button text for an item on the wishlist page
         *
         * @important
         * @param string $text
         * @param array  $row Array of row contents already added
         */
        $row['toItemPageButtonText'] = apply_filters('wcexwl_filter_wlpage_invalid_options_to_item_page_text', __('To Item Page', 'wcexwl'), $row);
        /**
         * Filters the 'Delete' button text for an item on the wishlist page
         *
         * @important
         * @param string $text
         * @param array  $row Array of row contents already added
         */
        $row['deleteButtonText'] = apply_filters('wcexwl_filter_wlpage_delete_btn_text', __('Delete', 'usces'), $row);
        /**
         * Filters the warning message displayed for an item on the wishlist page whose selected options are no
         * longer valid
         *
         * @important
         * @param string $text
         * @param array  $row Array of row contents already added
         */
        $row['changedOptsText'] = apply_filters(
            'wcexwl_filter_wlpage_item_opts_changed_info_text',
            __('Options have changed for this item. Please add to cart from the item details page.', 'wcexwl'),
            $row
        );
        /**
         * Filters the message displayed for an item on the wishlist page which has been deleted
         *
         * @important
         * @param string $text
         * @param array  $row Array of row contents already added
         */
        $row['deletedInfoText'] = apply_filters(
            'wcexwl_filter_wlpage_item_deleted_info_text',
            __('This item is no longer available for purchase.', 'wcexwl'),
            $row
        );

        return $row;
    }
}

ソースを伸ばす ソースを縮める


関数 #関数

Top ↑

  • buildWishlistRow — Adds meta data to a given wishlist row and returns it
  • executeAddToWishlist — Inserts item into wishlist table
  • executeDeletion — Deletes a wishlist item by ID
  • getAndBuildWishlistItems — Returns wishlist rows for a given member
  • getMemberId — Returns member ID for the current user
  • getPostIdByWishlistItemId — Returns the post ID of a wishlist item
  • getWishlistItemById — Returns a wishlist item by ID
  • getWishlistItemBySerial — Returns a wishlist item by serial
  • getWishlistItemCount — Returns number of items in the wishlist of a given user
  • getWishlistItems — Returns raw wishlist rows for a given member

  • 新規会員登録
  • ログイン
    • プラグイン一覧
    • 会社概要
    • リリース情報
    • よくある質問
    • お役立ちコラム
    • お問い合わせ
    • 個人情報保護方針
    • 特定商取引法に基づく表記
    • 情報セキュリティ基本方針
    • 利用規約

アイベック合同会社は「Welcart」「Amazon Pay」の公式パートナーです。

※Amazon、Amazon.co.jp、Amazon Payおよびそれらのロゴは、Amazon.com,inc.またはその関連会社の商標です。

© 2025 Aivec llc All Rights Reserved.