PHP: Output all blog articles from PHP, with link

Reading out all blog articles with link and PHP. Without WordPress functions.

For our “All articles” page, I wrote a small PHP script that reads all blog articles, makes a link out of it and then outputs it with the title.
Maybe this is useful for some of you, so I’ll leave the snippets here.

Standard variant

The standard variant if the page is not multilingual. Here we read the table “wp_posts”. If it is a “post” and also still published, then we output this as a link.

  $dbname="name";
  $dbhost="localhost";
  $dbuser="user";
  $dbpass="pass";

  $sql = "SELECT * FROM wp_posts WHERE post_status = 'publish' AND post_type = 'post' ORDER by post_date DESC";

  $db = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname) or die("Konnte keine Verbindung zur Datenbank herstellen");
	$sqlRes = mysqli_query($db, $sql);
  mysqli_close($db);

  $recordCount = mysqli_num_rows($sqlRes);

  for ($i = 0;$i < $recordCount;$i++) {
      $arCur = mysqli_fetch_array($sqlRes);
      echo "<li><a href=\"https://domain.net/?p=" . $arCur["ID"] . "\" title=\"zur Seite\">" . utf8_encode($arCur["post_title"]) . "</a></li>";
  }
?>

Variant for WPML and multilingualism

For our multilingual websites we use WPML. Here we have to extend the query a bit and determine the language of the post in addition to the ID of the post.

<?php
 //Datenbankzugriffsvariablen
  $dbname="ame";
  $dbhost="localhost";
  $dbuser="user";
  $dbpass="pass";

  //SQL Befehl zur Abfrage der Postings
  $sql = "SELECT wp_posts.*, wp_icl_translations.* FROM wp_posts LEFT JOIN wp_icl_translations ON wp_posts.ID = wp_icl_translations.element_id WHERE post_status = 'publish' AND post_type = 'post' and element_type = 'post_post' ORDER by ID DESC";

  //Datenbank öffnen, SQL-Befehl ausführen, Datenbank schließen
  $db = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname) or die("Konnte keine Verbindung zur Datenbank herstellen");
	$sqlRes = mysqli_query($db, $sql);
  mysqli_close($db);

  //Nun die Titel ausgeben
  $recordCount = mysqli_num_rows($sqlRes);

  for ($i = 0;$i < $recordCount;$i++) {
      $arCur = mysqli_fetch_array($sqlRes);
      $lang = $arCur["language_code"];

      $add = "";

      if ($lang === "en") {
        $add = "en/";
      }

      echo "<li><a href=\"https://domain.de/" . $add . "?p=" . $arCur["ID"] . "\" title=\"zur Seite\">" . utf8_encode($arCur["post_title"]) . "</a></li>\n";
  }
?>

Leave a Reply

Your email address will not be published. Required fields are marked *