將製作ejcees(中國象棋打譜程式)

分享和讨论Javascript相关的话题
回复
头像
ejsoon
一枝独秀
一枝独秀
帖子: 5367
注册时间: 2022年 11月 18日 17:36
为圈友点赞: 176 次
被圈友点赞: 204 次
联系:

Re: 將製作ejcees(中國象棋打譜程式)

帖子 ejsoon »

在wordpress中,如何寫php,拿到指定的媒體庫文件的地址?即使這個文件改名改路徑也能拿到?

代码: 全选

在 WordPress 中,要確保「即便檔案改名或路徑變動」依然能拿到正確的地址,唯一的準則就是:**永遠使用 Attachment ID(附件 ID)**。

WordPress 的媒體庫文件本質上是一種名為 `attachment` 的 **Post Type**。當你在後台修改圖片的標題或透過外掛重新命名檔案時,其 ID 是永遠不變的。

以下是實現這一點的幾種最佳實踐:

---

### 1. 最核心的方法:`wp_get_attachment_url()`

只要你有該文件的 ID,無論它的實體路徑怎麼變(例如從 `/2023/01/` 移到 `/2024/05/`),這個函式都能動態從資料庫中抓取當前最新的 URL。

```php
// 假設附件 ID 為 520
$attachment_id = 520;
$url = wp_get_attachment_url($attachment_id);

if ($url) {
    echo $url;
}
```
https://ejsoon.vip/
弈趣極光:享受思維樂趣
头像
ejsoon
一枝独秀
一枝独秀
帖子: 5367
注册时间: 2022年 11月 18日 17:36
为圈友点赞: 176 次
被圈友点赞: 204 次
联系:

Re: 將製作ejcees(中國象棋打譜程式)

帖子 ejsoon »

如何在wordpress的媒體庫中顯示文件大小?

代码: 全选

要在 WordPress 媒體庫中顯示文件大小,最簡單且不依賴外掛的方法是透過 PHP 代碼。這可以讓你直接在媒體庫的列表視圖中看到每個檔案佔用的空間(例如 1.2 MB)。

你可以將以下代碼添加到主題的 `functions.php` 檔案中:

---

### PHP 代碼實現

```php
/**
 * 在媒體庫列表增加「大小」欄位標題
 */
add_filter('manage_media_columns', 'add_file_size_column');
function add_file_size_column($columns) {
    $columns['file_size'] = '檔案大小';
    return $columns;
}

/**
 * 抓取並顯示每個媒體文件的實際大小
 */
add_action('manage_media_custom_column', 'display_file_size_column', 10, 2);
function display_file_size_column($column_name, $post_id) {
    if ($column_name === 'file_size') {
        // 獲取檔案路徑
        $file_path = get_attached_file($post_id);
        
        if (file_exists($file_path)) {
            // 獲取位元組數並轉換為易讀格式 (KB, MB)
            $size = filesize($file_path);
            echo size_format($size); 
        } else {
            echo '未知';
        }
    }
}

/**
 * 讓「大小」欄位支援點擊排序
 */
add_filter('manage_upload_sortable_columns', 'make_file_size_column_sortable');
function make_file_size_column_sortable($columns) {
    $columns['file_size'] = 'file_size';
    return $columns;
}
```

---

### 代碼功能詳解:

1.  **`manage_media_columns`**: 這會在媒體庫的表格標題列插入一個新的「檔案大小」欄位。
2.  **`get_attached_file($post_id)`**: 這是關鍵。它會根據我們之前聊過的 **Attachment ID** 找到伺服器上的實體路徑。
3.  **`size_format()`**: 這是 WordPress 內建的函數,會自動幫你把 $1048576$ bytes 轉換成 `1 MB` 這種人類看得懂的格式,非常方便。
4.  **排序功能**: 最後一段代碼讓你可以點擊標題,按檔案大小進行升冪或降冪排列,方便找出佔用空間的大檔案。

---

### 如何查看效果?

1.  保存 `functions.php` 後,進入後台 **媒體 > 媒體庫**。
2.  **重要:** 必須切換到 **「列表視圖 (List View)」**(點擊左上角的清單圖示),而不是預設的網格圖示。
3.  你就會看到多出一欄「檔案大小」。

### 補充:如果不想寫代碼?
如果你偏好使用外掛,可以搜尋 **"Filesize in Media Library"** 或 **"Admin Columns"**,這些外掛也提供類似的功能,並支援更多自定義欄位。

你目前是想清理網站空間,還是單純想在選取檔案時有個參考?
https://ejsoon.vip/
弈趣極光:享受思維樂趣
头像
ejsoon
一枝独秀
一枝独秀
帖子: 5367
注册时间: 2022年 11月 18日 17:36
为圈友点赞: 176 次
被圈友点赞: 204 次
联系:

Re: 將製作ejcees(中國象棋打譜程式)

帖子 ejsoon »

寫一個wordpress的short_code。

代码: 全选

寫一個wordpress的short_code。

一,short_code的名稱是「ejcees」,用法是[ejcees mode=single/mini]ejcees_content[/ejcees]。

二,它的html內容是:
    <div class="ejcees" mode="single/mini">ejcees_content</div>

三,當頁面上存在至少一個[ejcees]時,需要引入以下js,只需引入一次:
    <script src="ejceesobj.js"></script>
    <script>
      document.addEventListener('DOMContentLoaded', () => {
        const containers = document.querySelectorAll('.ejcees');
        containers.forEach(container => {
          const mode = container.getAttribute('mode');
          new Ejcees(container, mode);
        });
      });
    </script>

其中「<script src="ejceesobj.js"></script>」要改為:
$attachment_id = 19088;
$url = wp_get_attachment_url($attachment_id);
wp_enqueue_script('ejcees-obj-js')

四,ejcees_content要do_short_code以使其它short_code能用。

所有的代碼和注釋都要使用英文。


gemini fast:

代码: 全选

To implement this functionality, you can add the following code to your theme's `functions.php` file or a custom plugin. 

This implementation uses `wp_enqueue_script` to handle the JS file and `wp_add_inline_script` to inject the initialization logic. This ensures the scripts are only loaded once and only when the shortcode is actually present on the page.

```php
/**
 * Register the [ejcees] shortcode
 */
function register_ejcees_shortcode($atts, $content = null) {
    // 1. Define default attributes and extract them
    $options = shortcode_atts(array(
        'mode' => 'single', // Default mode
    ), $atts);

    // 2. Enqueue the external JS file via Attachment ID
    $attachment_id = 19088;
    $url = wp_get_attachment_url($attachment_id);

    if ($url) {
        // Register and enqueue the script
        wp_enqueue_script('ejcees-obj-js', $url, array(), null, true);

        // 3. Add the initialization inline script (runs only once)
        $inline_init_script = "
            document.addEventListener('DOMContentLoaded', () => {
                const containers = document.querySelectorAll('.ejcees');
                containers.forEach(container => {
                    const mode = container.getAttribute('mode');
                    if (typeof Ejcees !== 'undefined') {
                        new Ejcees(container, mode);
                    }
                });
            });
        ";
        wp_add_inline_script('ejcees-obj-js', $inline_init_script);
    }

    // 4. Process nested shortcodes within content
    $processed_content = do_shortcode($content);

    // 5. Return the HTML output
    return sprintf(
        '<div class="ejcees" mode="%s">%s</div>',
        esc_attr($options['mode']),
        $processed_content
    );
}
add_shortcode('ejcees', 'register_ejcees_shortcode');
```

### Key Technical Details:

* **Script Management:** Using `wp_enqueue_script` ensures that even if you use the shortcode multiple times on one page, the `ejceesobj.js` file is only requested by the browser once.
* **Inline Logic:** `wp_add_inline_script` attaches your custom DOMContentLoaded logic directly after the source file, maintaining the correct execution order.
* **Security:** `esc_attr()` is used on the `mode` attribute to prevent XSS (Cross-Site Scripting) if a user enters malicious data into the shortcode attribute.
* **Nested Content:** `do_shortcode($content)` allows you to place other shortcodes (like galleries or buttons) inside `[ejcees]...[/ejcees]`.

---

### Usage Example:
In your WordPress editor, you can now use it like this:

`[ejcees mode="mini"]This is my content or [another_shortcode][/ejcees]`
https://ejsoon.vip/
弈趣極光:享受思維樂趣
头像
ejsoon
一枝独秀
一枝独秀
帖子: 5367
注册时间: 2022年 11月 18日 17:36
为圈友点赞: 176 次
被圈友点赞: 204 次
联系:

Re: 將製作ejcees(中國象棋打譜程式)

帖子 ejsoon »

增加兩個參數:
一,[ejcees width="360"]

在html中就是style="width: 360px"

二,[ejcees inline]或[ejcees block]

在html中就是style="display: inline-block"或style="display: block; margin: 12px auto;"

這些參數都可以組合,組合時寫進同一個style中。

當沒寫這些參數時,默認值是「width=432 block」。

代码: 全选

根據您的需求,我更新了代碼。這版代碼增加了對 `width`、`inline` 與 `block` 參數的處理,並將它們整合到同一個 `style` 屬性中。

```php
/**
 * Updated [ejcees] shortcode with width and display layout parameters
 */
function register_ejcees_shortcode($atts, $content = null) {
    // 1. Define default attributes
    // 'width' defaults to 432, and we use a custom flag for display logic
    $atts = shortcode_atts(array(
        'mode'   => 'single',
        'width'  => '432',
        'inline' => false,
        'block'  => false,
    ), $atts);

    // 2. Logic for Display Style
    // Default is block if neither 'inline' nor 'block' is explicitly provided as an attribute
    $display_style = "";
    
    // Check if 'inline' or 'block' is present in the $atts array 
    // (Shortcode boolean attributes usually appear as keys with empty values if written without ="")
    if (isset($atts['inline']) && $atts['inline'] !== false) {
        $display_style = "display: inline-block;";
    } else {
        // Default behavior or explicit 'block'
        $display_style = "display: block; margin: 12px auto;";
    }

    // 3. Construct Style Attribute
    $width_val = esc_attr($atts['width']);
    $style_attr = "style=\"width: {$width_val}px; {$display_style}\"";

    // 4. Enqueue Scripts (using Attachment ID 19088)
    $attachment_id = 19088;
    $url = wp_get_attachment_url($attachment_id);

    if ($url) {
        wp_enqueue_script('ejcees-obj-js', $url, array(), null, true);

        $inline_init_script = "
            document.addEventListener('DOMContentLoaded', () => {
                const containers = document.querySelectorAll('.ejcees');
                containers.forEach(container => {
                    const mode = container.getAttribute('mode');
                    if (typeof Ejcees !== 'undefined') {
                        new Ejcees(container, mode);
                    }
                });
            });
        ";
        wp_add_inline_script('ejcees-obj-js', $inline_init_script);
    }

    // 5. Process Content and Output HTML
    $processed_content = do_shortcode($content);

    return sprintf(
        '<div class="ejcees" mode="%s" %s>%s</div>',
        esc_attr($atts['mode']),
        $style_attr,
        $processed_content
    );
}
add_shortcode('ejcees', 'register_ejcees_shortcode');
```

### 代碼邏輯說明:

1.  **默認值處理**:在 `shortcode_atts` 中設置 `width` 默認為 `432`。如果使用者沒有輸入 `inline`,邏輯會自動進入 `else` 分支,套用 `display: block; margin: 12px auto;`。
2.  **參數組合**:所有樣式都會被合併到一個 `$style_attr` 變數中,最終輸出為一個 `style="..."` 屬性。
3.  **用法範例**:
    * **默認(width=432 block)**: `[ejcees]內容[/ejcees]`
    * **修改寬度**: `[ejcees width="360"]內容[/ejcees]`
    * **設為行內**: `[ejcees inline="true" width="200"]內容[/ejcees]` 
        *(註:WordPress 的 shortcode 在處理純關鍵字參數如 `[ejcees inline]` 時,建議寫成 `inline="1"` 或 `inline="true"` 以確保屬性被正確解析)*。
4.  **嵌套支援**:保留了 `do_shortcode` 確保內部內容可以執行其他外掛的 shortcode。
https://ejsoon.vip/
弈趣極光:享受思維樂趣
回复

在线用户

正浏览此版面之用户: ejsoon 和 0 访客