2024年1月19日 Recordamu

WordPressプラグインの自作方法・作り方

WordPressプラグインの自作方法・作り方

プラグインの基本構成

WordPressプラグインを自作するには、最小限のファイル構成として以下のものが必要です:

  1. プラグイン用のフォルダ
  2. プラグイン用のPHPファイル

手順

1. プラグイン用のフォルダを作成

フォルダ名は自由ですが、わかりやすい名前をつけましょう。例:my-plugin

2. プラグイン用のPHPファイルを作成

フォルダ内にmy-plugin.phpというファイルを作成し、以下のコードを記載します:

<?php
/*
 * Plugin Name: マイプラグイン
 * Version: 1.0
 * Description: オリジナルのプラグインです。
 * Author: あなたの名前
 */

このコードにより、WordPressがプラグインを認識します。

3. プラグイン用の処理を記載

例えば、wp_footerアクションフックを使ってページのフッターに「Hello World!」を表示する簡単なプラグインを作成します:

<?php
/*
 * Plugin Name: マイプラグイン
 * Version: 1.0
 * Description: オリジナルのプラグインです。
 * Author: あなたの名前
 */

function hello_world() {
    echo 'Hello World!';
}
add_action('wp_footer', 'hello_world');

4. プラグインをアップロード

作成したフォルダをwp-content/pluginsディレクトリにアップロードします。

5. プラグインを有効化

WordPressの管理画面からプラグインを有効化します。

具体的な使用例と事例

CSS・JSファイルの読み込み

プラグインから独自のCSSやJavaScriptファイルを読み込む例:

<?php
function custom_files() {
    wp_enqueue_script('my-script', plugin_dir_url(__FILE__) . 'assets/function.js', array(), '1.0.0', true);
    wp_enqueue_style('my-style', plugin_dir_url(__FILE__) . 'assets/style.css', array(), '1.0.0', 'all');
}
add_action('wp_enqueue_scripts', 'custom_files');

このようにすることで、テーマが変わっても指定したスタイルやスクリプトが適用され続けます。

ショートコードの作成

最新の投稿を3件表示するショートコードの例:

<?php
function show_posts() {
    ob_start();
    $args = array('post_type' => 'post', 'posts_per_page' => 3);
    $the_query = new WP_Query($args);
    if ($the_query->have_posts()) {
        echo '<ul class="post-lists">';
        while ($the_query->have_posts()) {
            $the_query->the_post();
            echo '<li class="post-list" id="post-' . get_the_ID() . '">';
            echo '<a href="' . get_the_permalink() . '">' . get_the_title() . '</a>';
            echo '</li>';
        }
        echo '</ul>';
    }
    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode('showPosts', 'show_posts');

このショートコードを使うと、指定したページに最新の投稿リストを表示できます。

まとめ

WordPressプラグインの自作は、テーマに依存しないカスタム機能を実装するのに非常に有効です。これにより、テーマ変更時でも必要な機能を維持できます。自作プラグインを作成することで、より柔軟で強力なサイト運営が可能になります。

Contact

contact

We welcome you to contact us for more information about any of our services.

お気軽にお問い合わせください。

Create a web

We can provide a wide range of services from web direction / design / coding / WP integration / numerical analysis. Please feel free to contact us for an initial consultation.

Webディレクション/デザイン/コーディング/WP構築/数値解析まで、幅広く対応いたします。お気軽にご相談ください。

Japan information

We can help you do business for Japan.
Japan has its own rules and regulations, and the Japanese are sensitive to them.
We can help you with content (translation, sales, etc.) that takes into account communication that will work in Japan.

日本向けのビジネスのお手伝いをします。日本で通用するコミュニケーションを考慮した施策(翻訳や営業など)をご提供します。

Use our services

If you would like to use this service, please contact us. We also looking for people to collaborate and extend our services. Please feel free to contact us.

サービスの利用に関して、弊社までご連絡ください。また、コラボレーションしてサービスを拡張してくださる方も募集しています。

Contact