Collections Include

– Store PHP code in an external file, then 'include' the file into the page or post.

Typing in the WordPress editor is easy, but it is difficult to write and format code in that box. It is slower to make changes. What you write there is saved in the database, and many people say code should not go in the database. One alternative is to keep your code in PHP files. You can use a real code editor, and “include” them into the Page with a one line 'include' statement.

This example has the same query as Collections. For fun I have used a table layout. This time the page pulls the PHP code from another file:

Page will display:

Color Field
Minimalism
Sculpture
Symbolism and Symbology
Transcontinental Legacy

There are three steps to this 'include' file method:

  1. Make a new directory.
  2. Create the PHP file in the directory.
  3. Put one line of code in a page or post to pull in the file.

1. Make a new directory for the file. The wp-content directory, in the document root in your server, is where themes and plugins are stored. Here I created a new subdirectory arbitrarily named php-includes. (You may have to use sudo or your file browsers to set file permissions depending on your server.)

Code

2. Use a file editor to create a new file in this directory. I named this one collections-include.php. Copy and paste the following code into the file. Notice the use of a real <?php at the beginning instead of [insert_php] because this is an external PHP file.

<?php
$query = new AirpressQuery();
$query->setConfig("Artists_DB");
$query->sort("Name", "asc");
$query->table("Collections");
$data = new AirpressCollection($query);
if (count($data)){
  echo '<table style="table-layout:fixed; width:50%;">';
  foreach($data as $row){
    echo '<tr><td style="border-color:green; 
          background-color:#eeffee">'.
          $row["Name"].'</td></tr>';
  }
  echo '</table>';
}
?>

3. In a page or post, in the Text (NOT Visual) view, copy and paste this simple code to load the file:

[insert_php]
include $_SERVER["DOCUMENT_ROOT"].'wp-content/php-includes/collections-include.php';
[/insert_php]