国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

ホームページ バックエンド開発 PHPチュートリアル JSON 構(gòu)造に基づいた WordPress プラグイン オプションの作成

JSON 構(gòu)造に基づいた WordPress プラグイン オプションの作成

Dec 11, 2024 pm 03:48 PM

先日、WordPress プラグインのオプションを JSON ファイルで制御して、コード自體を調(diào)整することなく、將來的により簡(jiǎn)単に設(shè)定を追加できるようにするにはどうすればよいか考えていました。

この記事では、2 つのセクションと 3 つのフィールド/オプションで構(gòu)成される 1 つの設(shè)定ページを備えた、非常にシンプルな WordPress プラグインの例を示します。

完全なコードは Github にあります。

ベースのセットアップ

プラグインは最初は 3 つのファイルで構(gòu)成されています。

  • adventures.json
  • adventures.php
  • class.adventures.php

基本的なプラグイン登録を含むadventures.php:

<?php
/*
Plugin Name: Adventures
Plugin URI: https://mortenhartvig.dk
Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed pharetra nisi eu varius pellentesque. Aenean posuere, velit mollis sodales convallis, ipsum lectus feugiat nunc, ac auctor sapien enim eu metus.
Version: 1
Requires at least: 6.1
Requires PHP: 8.3
Author: Morten Hartvig
Author URI: https://mortenhartvig.dk
License: Do whatever you want
*/

define('ADV__PLUGIN_DIR', plugin_dir_path(__FILE__));
define('ADV__PLUGIN_VIEW', ADV__PLUGIN_DIR . 'views');
define('ADV__PLUGIN_SLUG', 'adv');

require_once ADV__PLUGIN_DIR . 'class.adventures.php';

(new Adventures());

空のクラスを含むclass.adventures.php:

<?php

class Adventures {
    public function __construct() {

    }
}

adventures.json には、プラグイン設(shè)定の JSON 構(gòu)造が含まれています:

{
    "settings": {
        "pages": [
            {
                "title": "Adventures",
                "capability": "manage_options",
                "slug": "adv"
            }
        ],
        "sections": [
            {
                "id": "portal_base",
                "title": "Base configuration",
                "description": "Lorem 1, ipsum dolor sit amet consectetur adipisicing elit. Cumque nulla in officiis. Laborum quisquam illo eaque, deserunt facere mollitia sint doloremque maiores, obcaecati reiciendis voluptate itaque iure fugiat quia architecto!",
                "view": "section"
            },
            {
                "id": "portal_appearance",
                "title": "Appearance",
                "description": "Lorem 2, ipsum dolor sit amet consectetur adipisicing elit. Cumque nulla in officiis. Laborum quisquam illo eaque, deserunt facere mollitia sint doloremque maiores, obcaecati reiciendis voluptate itaque iure fugiat quia architecto!",
                "view": "section"
            }
        ],
        "fields": [
            {
                "id": "adv_portal_key",
                "title": "Portal Key",
                "section": "portal_base",
                "type": "text",
                "placeholder": "Enter your portal key",
                "view": "field.text"
            },
            {
                "id": "adv_api_host",
                "title": "Host API",
                "section": "portal_base",
                "type": "text",
                "placeholder": "Enter API host",
                "default": "https://api.mortenhartvig.dk",
                "view": "field.text"
            },
            {
                "id": "adv_portal_theme",
                "title": "Theme",
                "section": "portal_appearance",
                "type": "select",
                "options": {
                    "rounded.v1": "Round (V1)",
                    "squared.v1": "Square (V1)",
                    "standard": "Standard"
                },
                "default": "standard",
                "view": "field.select"
            }
        ]
    }
}

JSONデータの読み込み

設(shè)定のプロパティを作成し、set_settings():
を呼び出します。

private $settings;

public function __construct() {
    $this->set_settings();
}

set_settings() と get_json_data() を作成します:

private function set_settings() {
    $data = $this->get_json_data();

    $this->settings = $data['settings'];
}

private function get_json_data() {
    $file = ADV__PLUGIN_DIR . 'adventures.json';

    if (!file_exists($file)) {
        die('adventures.json not found');
    }

    return json_decode(file_get_contents($file), true);
}

die(print_r($this->settings)) を __construct に追加すると、設(shè)定が実際にロードされたことを確認(rèn)できます。

Creating WordPress plugin options based on a JSON structure

設(shè)定ページ

コンストラクターから init_hooks() を呼び出します:

public function __construct() {
    $this->set_settings();
    $this->init_hooks();
}

init_hooks() を作成します:

private function init_hooks() {
    add_action('admin_menu', [$this, 'register_settings_pages']);
}

register_settings_pages() と settings_page_callback() を作成します。

public function register_settings_pages() {
    foreach ($this->settings['pages'] as $page) {
        add_options_page($page['title'], $page['title'], $page['capability'], $page['slug'], [$this, 'settings_page_callback']);    
    }
}

public function settings_page_callback() {
    $this->render('settings.php');
}

render() を作成します:

private function render($filename, $args) {
    if (is_array($args)) {
        $value = get_option($args['id']);

        if (empty($value) && isset($args['default'])) {
            $value = $args['default'];
        }

        $args = array_merge($args, ['value' => $value]);
    }

    $file = ADV__PLUGIN_VIEW . $filename;

    if (!str_ends_with($file,'.php')) {
        $file .= '.php';
    }

    if(!file_exists($file)) {
        die('File not found ' . $filename);
    }

    require $file;
}

views/settings.php を作成します:

<div>



<p><img src="/static/imghw/default1.png"  data-src="https://img.php.cn/upload/article/000/000/000/173390329693560.jpg"  class="lazy" alt="Creating WordPress plugin options based on a JSON structure" /></p>

<h3>
  
  
  Sections
</h3>

<p>Add another action in init_hooks:<br>
</p>

<pre class="brush:php;toolbar:false">private function init_hooks() {
    add_action('admin_menu', [$this, 'register_settings_pages']);
    add_action('admin_init', [$this, 'register_settings_sections']);
}

register_settings_sections() と settings_section_callback() を作成します:

public function register_settings_sections() {
    foreach ($this->settings['sections'] as $section) {
        add_settings_section($section['id'], $section['title'], [$this, 'settings_section_callback'], ADV__PLUGIN_SLUG, $section);
    }
}

public function settings_section_callback($args) {
    $this->render($args['view'], $args);
}

views/section.php を作成します:

<p>
    <?php echo $args['description']; ?>
</p>

フィールド

init_hooks に 3 番目のアクションを追加します:

private function init_hooks() {
    add_action('admin_menu', [$this, 'register_settings_pages']);
    add_action('admin_init', [$this, 'register_settings_sections']);
    add_action('admin_init', [$this, 'register_settings_fields']);
}

register_settings_fields() と settings_field_callback() を作成します:

public function register_settings_fields() {
    foreach ($this->settings['fields'] as $field) {
        add_settings_field($field['id'], $field['title'], [$this, 'settings_field_callback'], ADV__PLUGIN_SLUG, $field['section'], $field);

        register_setting(ADV__PLUGIN_SLUG, $field['id']);
    }
}

public function settings_field_callback($args) {
    $this->render($args['view'], $args);
}

views/field.select.php を作成します:

<?php

$html_options = '';

foreach ($args['options'] as $key => $val) {
    $html_options .= sprintf('<option value="%s" %s >%s</option>', $key, selected($args['value'], $key, false), $val);
}

printf('<select name="%s">



<p>Create views/field.text.php:<br>
</p>

<pre class="brush:php;toolbar:false"><?php

printf('<input name="%s">



<h3>
  
  
  Saving
</h3>

<p>To view and save your options add a form to settings.php:<br>
</p>

<pre class="brush:php;toolbar:false"><div>



<p>Change an option and attempt to <em>Save</em>. The save should be successful.</p>

<p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173390329893991.jpg" class="lazy" alt="Creating WordPress plugin options based on a JSON structure"></p>

<p>Your settings are now saved and can be accessed throughout the site via:<br>
</p>

<pre class="brush:php;toolbar:false"><?php
echo get_option('adv_portal_theme'); // squared.v1

新しいフィールドの追加

以下の JSON を Adventures.json に追加します:

{
    "id": "adv_api_token",
    "title": "Host API Token",
    "section": "portal_base",
    "type": "text",
    "placeholder": "Enter API host token",
    "default": "",
    "view": "field.text"
}

設(shè)定に自動(dòng)的に追加されます:

Creating WordPress plugin options based on a JSON structure

以上がJSON 構(gòu)造に基づいた WordPress プラグイン オプションの作成の詳細(xì)內(nèi)容です。詳細(xì)については、PHP 中國(guó)語 Web サイトの他の関連記事を參照してください。

このウェブサイトの聲明
この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當(dāng)する法的責(zé)任を負(fù)いません。盜作または侵害の疑いのあるコンテンツを見つけた場(chǎng)合は、admin@php.cn までご連絡(luò)ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脫衣畫像を無料で

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード寫真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

寫真から衣服を削除するオンライン AI ツール。

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡(jiǎn)単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中國(guó)語版

SublimeText3 中國(guó)語版

中國(guó)語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強(qiáng)力な PHP 統(tǒng)合開発環(huán)境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

PHPに認(rèn)証と承認(rèn)を?qū)g裝するにはどうすればよいですか? PHPに認(rèn)証と承認(rèn)を?qū)g裝するにはどうすればよいですか? Jun 20, 2025 am 01:03 AM

tosecurelyhandLeauthenticationAndauthorizationInizationInization、followTheSteps:1.LwayShashPasswordswithPassword_hash()andverifyusingpassword_verify()、usepreparedStatementStatementStatementStatementStatementStain、andstoreUserdatain $ _SessionAfterlogin.2.implementRementRementRementRementRementRementRementRole

PHPでファイルアップロードを安全に処理するにはどうすればよいですか? PHPでファイルアップロードを安全に処理するにはどうすればよいですか? Jun 19, 2025 am 01:05 AM

PHPでファイルアップロードを安全に処理するために、コアはファイルタイプを確認(rèn)し、ファイルの名前を変更し、権限を制限することです。 1。Finfo_File()を使用して実際のMIMEタイプを確認(rèn)し、Image/JPEGなどの特定のタイプのみが許可されます。 2。uniqid()を使用してランダムファイル名を生成し、非webルートディレクトリに保存します。 3. PHP.iniおよびHTMLフォームを介してファイルサイズを制限し、ディレクトリ権限を0755に設(shè)定します。 4. Clamavを使用してマルウェアをスキャンしてセキュリティを強(qiáng)化します。これらの手順は、セキュリティの脆弱性を効果的に防止し、ファイルのアップロードプロセスが安全で信頼性が高いことを確認(rèn)します。

PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? PHPの==(ゆるい比較)と===(厳密な比較)の違いは何ですか? Jun 19, 2025 am 01:07 AM

PHPでは、==と==の主な違いは、タイプチェックの厳格さです。 ==タイプ変換は比較の前に実行されます。たとえば、5 == "5"はtrueを返します。===リクエストは、trueが返される前に値とタイプが同じであることを要求します。たとえば、5 === "5"はfalseを返します。使用シナリオでは、===はより安全で、最初に使用する必要があります。==は、タイプ変換が必要な場(chǎng)合にのみ使用されます。

PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? PHP(、 - 、 *、 /、%)で算術(shù)操作を?qū)g行するにはどうすればよいですか? Jun 19, 2025 pm 05:13 PM

PHPで基本的な數(shù)學(xué)操作を使用する方法は次のとおりです。1。追加標(biāo)識(shí)は、整數(shù)と浮動(dòng)小數(shù)點(diǎn)數(shù)をサポートし、変數(shù)にも使用できます。文字列番號(hào)は自動(dòng)的に変換されますが、依存関係には推奨されません。 2。減算標(biāo)識(shí)の使用 - 標(biāo)識(shí)、変數(shù)は同じであり、タイプ変換も適用されます。 3.乗算サインは、數(shù)字や類似の文字列に適した標(biāo)識(shí)を使用します。 4.分割はゼロで割らないようにする必要がある分割 /標(biāo)識(shí)を使用し、結(jié)果は浮動(dòng)小數(shù)點(diǎn)數(shù)である可能性があることに注意してください。 5.モジュラス標(biāo)識(shí)を採取することは、奇妙な數(shù)と偶數(shù)を判斷するために使用でき、負(fù)の數(shù)を処理する場(chǎng)合、殘りの兆候は配當(dāng)と一致しています。これらの演算子を正しく使用するための鍵は、データ型が明確であり、境界の狀況がうまく処理されるようにすることです。

PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? PHPのNOSQLデータベース(Mongodb、Redisなど)とどのように対話できますか? Jun 19, 2025 am 01:07 AM

はい、PHPは、特定の拡張機(jī)能またはライブラリを使用して、MongoDBやRedisなどのNOSQLデータベースと対話できます。まず、MongoDBPHPドライバー(PECLまたはComposerを介してインストール)を使用して、クライアントインスタンスを作成し、データベースとコレクションを操作し、挿入、クエリ、集約、その他の操作をサポートします。第二に、PredisライブラリまたはPhpredis拡張機(jī)能を使用してRedisに接続し、キー価値設(shè)定と取得を?qū)g行し、高性能シナリオにPhpredisを推奨しますが、Predisは迅速な展開に便利です。どちらも生産環(huán)境に適しており、十分に文書化されています。

最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? 最新のPHP開発とベストプラクティスを最新の狀態(tài)に保つにはどうすればよいですか? Jun 23, 2025 am 12:56 AM

postaycurrentwithpdevellyments andbest practices、follow keynewsourceslikephp.netandphpweekly、egagewithcommunitiessonforums andconferences、keeptooling and gradivallyadoptnewfeatures、andreadorcontributeTopensourceprijeprijeprijeptrijeprijeprests.

PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? PHPとは何ですか、そしてなぜそれがWeb開発に使用されるのですか? Jun 23, 2025 am 12:55 AM

PhpBecamepopularforwebdevelopmentduetoitseaseaseaseaseasease、SeamlessintegrationWithhtml、widespreadhostingsupport、andalargeecosystemincludingframeworkelavelandcmsplatformslikewordspresspressinsinsionsisionsisionsisionsisionsionsionsisionsionsionsisionsisions

PHPタイムゾーンを設(shè)定する方法は? PHPタイムゾーンを設(shè)定する方法は? Jun 25, 2025 am 01:00 AM

tosettherighttimezoneInphp、usedate_default_timezone_set()functionthestthestofyourscriptwithavalididentifiersiersuchas'america/new_york'.1.usedate_default_timezone_set()beforeanydate/timefunctions.2.2.Altertentally、confuturethephp.inifilebyset.

See all articles