WordPressに、外部データベースに依存し、この目的でwpdbクラスを使用しているカスタムページテンプレートがあります。
これは私のコードです:
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
</header><!-- .entry-header -->
<?php
class StudentsDatabase
{
private $db;
public function __construct() {
try {
$this->db = new wpdb(DB_USER, DB_PASSWORD, 'students_db', DB_HOST);
$this->db->show_errors();
} catch (Exception $e) {
echo $e->getMessage();
}
}
public function getStudentById($student_id)
{
return $this->db->get_results("SELECT * FROM `students` WHERE id=$student_id");
}
public function getSchoolByAreaCode($area_code)
{
return $this->db->get_results("SELECT * FROM `schools` WHERE area_code=$area_code;--");
}
}
$Students_DB = new StudentsDatabase();
$student_one = $Students_DB->getStudentById(1);
$school_one = $Students_DB->getSchoolByAreaCode(1);
?>
<div class="entry-content">
<?php
//do something with $student_one and $school_one ...
the_content();
?>
</div><!-- .entry-content -->
さて、これが正しい方法かどうか疑問に思いました。実際には、セキュリティ面またはその他の「その他」の面で。
ページのテンプレート自体から外部db呼び出しを行うのは、ちょっと大雑把な感じがします。これらの関数を外部ファイルに登録してから、テンプレート内で使用する必要がありますか?
最も「クリーンな」方法は、テーマのAPIとなるプラグインを実装することだと思います。もちろん、Wordpressには(これまでのところ)依存関係マネージャーがないため、それがあなた自身の目的のためだけのテーマであるかどうかによって異なります。
要約すると、テーマではこのAPIを使用します。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加