SQLでサーバーから直接記事を抜き出す

SQLでサーバーから直接記事を抜き出す

基本的にはまず、データーベースのテーブルのつながりを確認する。
書出しておくと分かりやすい。
下記のソースを元に書き換えていくが、phpMyadmin上の「SQL」タブで取得の確認を行いながら記述していくと良い。

<?php
  ini_set("display_errors", 1);

  global $wpdb;
  $db_name = 'データベース ネーム';
  $db_user = 'データベース ユーザー名';
  $db_passwd = 'データベース パスワード';
  $db_host = 'データベース ホスト名';
  $table_prefix = 'wp_';

  $another_wpdb = new wpdb($db_user, $db_passwd, $db_name, $db_host);
  $another_wpdb->set_prefix($table_prefix);

  $query = "
    SELECT
      a.ID,
      a.post_title,
      a.post_date,
      a.guid as permalink,
      c.guid as image_url
    FROM
      `wp_posts` as a
    left join
      wp_postmeta as b on a.ID = b.post_id and b.meta_key = 'detail_mv'
    left join
      wp_posts as c on b.meta_value= c.ID
    where
      a.post_status = 'publish'
    and
      a.post_type = 'post'
    order by a.post_date desc
    limit 2
  ";

  $magazine = $another_wpdb->get_results( $query );

  //var_dump($magazine); exit;

?>

<body>
<div id="wrapper">
  <div id="contents">
    <main role="main">
    <ul>
 <?php foreach ($magazine as $value) : ?>
  <li>
  <a href="<?php echo $value->permalink; ?>" target="_brank">
  <div class="thumb" style="background-image: url(<?php echo $value->image_url; ?>);"></div>
  <div class="detail">
    <p class="date"><?php echo date('Y.m.d', strtotime($value->post_date)); ?></p>
    <p class="txt"><?php echo $value->post_title; ?></p>
  </div>
  </a>
  </li>
  <?php endforeach; ?>
  </ul>
    </main>
  <!-- /#contents -->
  </div>
<!-- /wrapper -->
</div>
</body>

■抜き出す要素が多い場合の例

  $query_sanchu = "
    SELECT
      a.ID,
      a.post_title,
      a.post_date,
      a.guid as permalink,
      c.guid as image_url,
      d.meta_value,
      g.slug
    FROM
      `wp_posts` as a
    left join
      `wp_postmeta` as b on a.ID = b.post_id and b.meta_key = 'detail_mv'
    left join
      `wp_posts` as c on b.meta_value= c.ID
    left join
      `wp_postmeta` as d on a.ID = d.post_id and d.meta_key = 'corporate_postview'
    left join
      `wp_term_relationships` as e on a.ID = e.object_id
    left join
      `wp_term_taxonomy` as f on e.term_taxonomy_id = f.term_taxonomy_id
    left join
      `wp_terms` as g on f.term_id = g.term_id
    where
      a.post_status = 'publish'
    and
      a.post_type = 'post'
    order by
      a.post_date desc
  ";