增加兩個參數:
一,[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。