just a personal cut & paste page

martedì, luglio 26, 2005

DRUPAL: PHP page snippets

PHP page snippets: putting dynamic content into your main page

Once Drupal is installed you will notice an option under CREATE CONTENT to create a PAGE. It is a standard out-of-the-box drupal feature and when creating a PAGE you have 3 filter options when submitting i.e. Filtered HTML, Full HTML or PHP.

The PHP Snippets below are intended for use within a drupal page filtered as PHP that simply enables you to "pull" specific content from your drupal database. Allowing you to create dynamic and sophisticated page layouts such those found at busy portals, such as www.mtv.com or www.yahoo.com.

Make sure you check the custom block examples as well.

  • Very simple to use and implement. Copy n paste snippets into your page
  • Allows users to insert "block style" content in the main page
  • build simple or sophisticated main page layouts with dynamic content
  • pull specific content from your drupal database to insert into a page

PLEASE NOTE! The following snippets are user submitted. Use at your own risk! For users who have setup drupal using an alternate database to the default (MYSQL), please note that the snippets may contain some database queries specific to MYSQL.

How to insert and use the PHP Snippets in your pages

The PHP SNIPPETS come with a brief introduction on what it does and if it only works with specific versions of Drupal.

Some are very similar to how you SETUP CUSTOM BLOCKS WITH CONTENT THAT APPEAR IN THE SIDEBARS but the snippets below are intended for use within your main NODE page as opposed to your sidebars.

Once you get used to how the PHP Snippets work and if you are familiar with how to setup up a HTML table or using DIVs, you can mix snippets together in the same page creating sophisticated layouts like those found at http://www.mtv.com or http://www.yahoo.com.

  1. Go to CREATE CONTENT -->> PAGE
  2. Give your page a TITLE
  3. In the BODY text area, paste in your PHP Snippet. Make sure you include the opening and closing PHP statements and remove any extra spaces, line breaks after the final ?> which tells drupal that this is the end of the php page.
  4. Select the PHP CODE filter.
  5. Click SUBMIT or PREVIEW to view your page.

More sophisticated layout/styling of node pages

The following is intended for people not familiar with PHP coding and illustrates how to apply styling to content inserted into a page using PHP.

Here is an example of a very simple PHP snippet that displays the Site slogan.

<?php
/**
* the following displays the site slogan
*
*/
print variable_get("site_slogan", "");
?>

Click for a simple example of how to add styling to the content displayed by the php snippet .

Using some simple HTML functions, such as creating a table or using DIVS, you can start creating much more sophisticated layouts using multiple snippets in the same page. For some guidance and tips it is worth looking at a more sophisticated php Snippet that inserts the site mission and a list of upcoming events in a 2 column table side by side, followed by a list of the recent weblog entries.

!--------------!---------------!
!--------------!---------------!
!------site----!--upcoming-----!
!----mission---!---events------!
!--------------!---------------!
!--------------!---------------!
!--------------!---------------!
!----recent weblog entries-----!
!--------------!---------------!
!--------------!---------------!

How to use the PHP Snippets with the front_page.module

USING PHP SNIPPETS WITH THE FRONT_PAGE.MODULE

Probably the most common use of php snippets will be the front page of your site.

To use any of these snippets using the front_page.module (allows you to specify a "splash" page to your site and different front pages for anonymous/authenticated users) Simply follow these steps once you have the front_page.module installed properly:

Step 1: Go to ADMINISTER -->> SETTINGS -->> FRONT_PAGE

Step 2: In the teaxt areas available, paste in your PHP Snippet(s).

Step 3: Select the ALLOW EMBEDDED PHP option.

Step 4: Select if you want a FULL/THEMED Front Page.

Step 5: Click on SAVE CONFIGURATION once you are happy with your front_page settings.

A guide to submitting your own PHP snippets

Please post your own snippets up here for others and follow these simple guidelines.

  1. Click on ADD CHILD PAGE from the main page in this section (PHP PAGE SNIPPETS: PUTTING DYNAMIC CONTENT INTO YOUR MAIN PAGE ).
  2. Give your snippet a short and obvious title so it is easy for others to see what your snippet does.
  3. Please include a simple introduction at the top of your PHP Snippet which explains:
    • What the snippet does
    • Which versions of Drupal has it been tested with
    • Any extra information for newbies that you think is relevant

Countdown (x) days to a specific date and display a dynamic message

PLEASE NOTE! The following snippet is user submitted. Use at your own risk! For users who have setup drupal using an alternate database to the default (MYSQL), please note that the snippets may contain some database queries specific to MYSQL.

<?php
/**
* This php snippet displays (x) days left to a specific event
*
*
* Change the values for keyMonth, keyDay and keyYear to suit
*
*
* Tested and works with drupal 4.6 and 4.5
*/
$keyMonth = 7;
$keyDay = 14;
$keyYear = 2005 ;
$month = date(F);
$mon = date(n);
$day = date(j);
$year = date(Y);
$hours_left = (mktime (0,0,0,$keyMonth ,$keyDay,$keyYear) - time ())/3600;
$daysLeft = ceil( $hours_left/24);
$z = (string)$daysLeft ;
if (
$z > 1) {
print
"There are <font size=\"4\" color=\"red\">" ;
print
$z;
print
"</font> days left until whatever happens</p>" ;
}
?>

Create a list of node titles of a specific type, within certain dates/times

<?php
/**
* Creates a list of node titles of a specific type, within certain dates
* with a link to each node.
*
* To change which type is listed, simply edit the $node_type string.
* To change the starting date, simply change the $start_stamp.
* To change the ending date, simply change the $end_stamp.
*
* This works with drupal 4.6
*/
$node_type = "image";
$start_stamp = 'June 9 2005';
$end_stamp  = 'June 10 2005' ;
$start_stamp = strtotime($start_stamp);
$end_stamp = strtotime($end_stamp);
$sql = "SELECT node.title, node.nid FROM node WHERE node.created < $end_stamp AND node.created > $start_stamp AND node.type = '$node_type'" ;
$output .= "<ul>";
$result = db_query($sql);
while (
$anode = db_fetch_object($result)) {
$output .= "<li>".l($anode-> title, "node/$anode->nid")."</li>";
}
$output .= "</ul>";
return
$output ;
?>

display (x) random thumbnails in a page

PLEASE NOTE! The following snippet is user submitted. Use at your own risk! For users who have setup drupal using an alternate database to the default (MYSQL), please note that the snippets may contain some database queries specific to MYSQL.

<?php
/**
* This php snippet displays (x) random thumbnails with a link to
* the full images in a page.
*
* (assumes you already have the IMAGE.MODULE installed)
*
* To increase/decrease the number of thumbnails listed
* change the $thumbs field to suit.
*
* Tested and works with drupal 4.6
*/
$thumbs = 0;
while (
$thumbs< 10) {
$images = (image_get_random($count = 1, $tid = 0));
print
l(image_display($images[ 0], 'thumbnail'),'node/'.$images [0]->nid, array(), null, null, FALSE, TRUE);
$thumbs ++;
}
?>

Display a list of (x) most recent weblog entries

PLEASE NOTE: The php snippets are user submitted and it is impossible to check every one, so use at your own risk. For users who have setup drupal using an alternate database to the default, please note that the snippets may contain some database queries that may or may not work.

<?php
/**
* the following displays a list of the 10 most recent weblog titles
* and links to the full weblogs. If you want to increase/reduce
* the number of titles displayed..simply change $listlength value
*
* This php snippet works with drupal 4.6.
*
*/
$listlength= "10";
$output = node_title_list(db_query_range (db_rewrite_sql("SELECT n.nid, n.title, n.created FROM {node} n WHERE n.type = 'blog' AND n.status = 1 ORDER BY n.created DESC"), 0, $listlength));
print
$output;
?>

Display a list of (x) node titles of a specific type

<?php
/**
* Creates a list of node titles of a specific type
* with a link to each node.
*
* To change which type is listed, simply edit the $node_type string.
* To change the number of node titles listed, simply edit the $list_no number.
*
* This works with drupal 4.5 and drupal 4.6
*/
$node_type = "flexinode-1";
$list_no =5;
$sql = "SELECT node.title, node.type, node.nid FROM node WHERE node.type = '$node_type' LIMIT $list_no";
$output .= "<ul>";
$result = db_query($sql);
while (
$anode = db_fetch_object ($result)) {
$output .= "<li>" .l($anode->title , "node/$anode->nid")."</li>";
}
$output .= "</ul>";
return
$output;
?>

Display a list of (x) upcoming events in a scrolling box without javascript

PLEASE NOTE! The following snippets are user submitted. Use at your own risk! For users who have setup drupal using an alternate database to the default (MYSQL), please note that the snippets may contain some database queries specific to MYSQL.

<?php
/**
* The following snippet displays the next 10 upcoming events
* in a scrolling box that is set in a simple DIV styled inline.
* To increase or decrease the number of events listed just change
* the $listlength value
*
* no javascript is required and the current
* height, width is 150 X 320 pixels.
* to increase decrease that simply change the values for
* the $boxheight and $boxwidth
*
* works with most popular browsers
* Tested in IE6, Mozilla Firefox 1.0 & 1.5, and NN7
*
* Tested and works with with drupal 4.5.x and Drupal 4.6.x
*
*
*/
$listlength="15";
$boxheight= "150px";
$boxwidth="320px";
print
"<h1>Upcoming Events</h1><div style=\"unicode-bidi:bidi-override; direction:rtl; display:block; width:$boxwidth; height:$boxheight; overflow:auto; padding-left:10px; border:1px solid #ba8; \"><div dir=\"ltr\"><p>" ;
print  
event_block_upcoming($limit=$listlength );
print
"</p></div></div>";
?>

Display a list of a certain content type, with teasers

<?php
/**
* This php snippet displays content of a specified type, with teasers
*
* To change the type of content listed, change the $content_type.
*
* Works with drupal 4.6
*/
  
$content_type = 'story';
  
$result1 = pager_query(db_rewrite_sql("SELECT n.nid , n.created FROM {node} n WHERE n.type = '$content_type' AND n.status = 1 ORDER BY n.created ASC"));
  while (
$node = db_fetch_object($result1)) {
    
$output .= node_view(node_load(array('nid' => $node ->nid)), 1);
  }
print
$output ;
?>

Display a list of category titles with links to the full term

Please note: These snippets are user submitted. Use at your own risk. For users who have setup Drupal using a database other than the default (MySQL), please note that the snippets may contain some database queries specific to MySQL.

<?php
/**
* Creates a list of category titles with a link to each category term.
* And the number of items in each term in brackets. (x)
*
* Category term title (x) and link to full term
* date of last update
*
*
* This works with drupal 4.6 and 4.5.
*
* If you improve this snippet please post a new comment below.
*
*/
$result = db_query("SELECT d.tid, d.name, MAX(n.created ) AS updated, COUNT(*) AS count FROM {term_data} d INNER JOIN {term_node} USING (tid) INNER JOIN {node} n USING (nid) WHERE n.status = 1 GROUP BY d.tid, d.name ORDER BY updated DESC, d.name");
  
$items = array();
  while (
$category = db_fetch_object($result)) {
    
$items[] = l ($category->name .' (' . $category->count .')', 'taxonomy/term/'. $category->tid) .'<br />' . t('%time ago', array('%time' => format_interval(time() - $category-> updated)));
  }
print
theme('item_list', $items);
?>

Display a list of node titles from a specific category

PLEASE NOTE! The following snippets are user submitted. Use at your own risk! For users who have setup drupal using an alternate database to the default (MYSQL), please note that the snippets may contain some database queries specific to MYSQL.

<?php
/**
* Creates a list of node titles from a specific category
* with a link to each node.
*
* To change which taxonomy is listed, simply edit the $taxd_id number.
* To change the number of node titles listed, simply edit the $list_no number.
*
* This works with drupal 4.5 and drupal 4.6
*/
$taxo_id = 1;
$list_no =5;
$sql = "SELECT node.title, node.nid FROM node INNER JOIN term_node ON node.nid = term_node.nid WHERE term_node.tid = $taxo_id LIMIT $list_no";
$output .= "<ul>";
$result = db_query($sql);
while (
$anode = db_fetch_object ($result)) {
$output .= "<li>" .l($anode->title , "node/$anode->nid")."</li>";
}
$output .= "</ul>";
return
$output;
?>

Display a list of the next (x) upcoming events

PLEASE NOTE! The following snippets are user submitted. Use at your own risk! For users who have setup drupal using an alternate database to the default (MYSQL), please note that the snippets may contain some database queries specific to MYSQL.

<?php
/**
* the following displays a list of the 10 upcoming event titles and
* links to their full event nodes. To increase/decrease
* the number of titles displayed..simply change the $listlength value
*
* Works with drupal 4.5.x and drupal 4.6
*/
  
$listlength= "10";
  print
event_block_upcoming($limit = $listlength);
?>

Display a list with last post w/links

This is a very useful code (at least for me). It shows a list of node types, node posts count, last post date and a link to the last node published.

<?php
$header
= array ('Content', 'Count', 'Last post date','Last post');
$rows = array();
$q = "SELECT n.type as tipo,count(n.type) as cant,max(DATE_FORMAT(FROM_UNIXTIME(n.changed ), '%Y-%m-%d')) as lastpost
FROM
{node} n
group by n.type"
;
$result = db_query ($q);
while (
$row = db_fetch_object ( $result ) )
{
  
$q = "SELECT max(n.nid) as max FROM {node} n where n.type='$row- >tipo'";
  
$result2 = db_query ($q );
  
$r = db_fetch_object ( $result2 );
  
$q = "SELECT n.nid as nid,n.title as title FROM {node} n where n.nid=$r->max";
  
$result2 = db_query ($q);
  
$r = db_fetch_object ( $result2 );
  
$link = l($r->title, "node/".$r->nid);
  
$rows[] = array ( 'data' => array ( t($row ->tipo), $row->cant ,$row->lastpost, $link  )) ;
}
if (!
$rows) {
  
$rows[] = array(array('data' => t('No log data available.'), 'colspan' => 2));
}
print
theme('table', $header , $rows);
?>

Display different page content to anonymous and authenticated users

PLEASE NOTE! The following snippets are user submitted. Use at your own risk! For users who have setup drupal using an alternate database to the default (MYSQL), please note that the snippets may contain some database queries specific to MYSQL.

<?php
/**
* The following simple snippet
* displays different information to anonymous/logged in users within a page.
*
* This works with drupal 4.5 and drupal 4.6
*/
global $user;
if (
$user ->uid) {
    return
"This message is only visible for logged-in users.";
}
if (!
$user->uid) {
    return
"This message is only visible for not-logged-in users." ;
}
?>

Display the (x) most recent nodes in full from a specific category

PLEASE NOTE! The following snippet is user submitted. Use at your own risk! For users who have setup drupal using an alternate database to the default (MYSQL), please note that the snippets may contain some database queries specific to MYSQL.

<?php
/**
* This php snippet displays the most recent node in full
* from a specific category
*
* To increase/decrease the number of nodes listed
* change the $list_length value to suit.
*
* Works with drupal 4.6.x & 4.5.x
*
* Snippet submitted by Robert Garrigos (robertgarrigos)
*/
$taxo_id = 10;
$list_length = 1;
$sql = "SELECT * FROM node INNER JOIN term_node ON node.nid = term_node.nid WHERE term_node.tid = $taxo_id ORDER BY node.created DESC LIMIT $list_length" ;
$result = db_query($sql );
while (
$anode = db_fetch_object($result)) {
$output .= theme('node', $anode, $teaser = TRUE, $page = FALSE);
}
print
$output;
?>

Display the (x) most recent weblog entries from a specific user

PLEASE NOTE! The following snippets are user submitted. Use at your own risk! For users who have setup drupal using an alternate database to the default (MYSQL), please note that the snippets may contain some database queries specific to MYSQL.

<?php
/**
* the following displays a list of the 10 most recent weblog titles
* and links to the full weblogs of a certain user.
* If you want to increase/reduce
* the number of titles displayed..simply change the $listlength value
*
* for a different user change the $userid value
*
* works with drupal 4.6.
*
*/
$listlength="10";
$userid="8" ;
$output = node_title_list(db_query_range (db_rewrite_sql("SELECT n.nid, n.title, n.created FROM {node} n WHERE n.type = 'blog' AND n.uid = $userid AND n.status = 1 ORDER BY n.created DESC"), 0, $listlength));
print
$output;
?>

Display the (x) most recent weblog entries with teasers & info.

PLEASE NOTE! The following snippets are user submitted. Use at your own risk! For users who have setup drupal using an alternate database to the default (MYSQL), please note that the snippets may contain some database queries specific to MYSQL.

<?php
/**
* This php snippet displays the 10 most recent weblog entries with
* teaser & info.
*
* To increase/decrease the number of weblogs listed
* change the $listlength field to suit.
*
* Works with drupal 4.6
*/
  
$listlength= 10;
  
$result1 = pager_query(db_rewrite_sql ("SELECT n.nid, n.created FROM {node} n WHERE n.type = 'blog' AND n.status = 1 ORDER BY n.created DESC"), variable_get('default_nodes_main', $listlength));
  while (
$node = db_fetch_object($result1)) {
    
$output .= node_view(node_load(array('nid' => $node->nid)), 1);
  }
print
$output;
?>

Display/hide content from a specific IP address within a page

PLEASE NOTE These snippets are user submitted. Use at your own risk. For users who have setup drupal using an alternate database to the default (MYSQL), please note that the snippets may contain some database queries specific to MYSQL.

<?php
/**
* this Snippet allows you to display content ONLY to a visitor from
* a specific IP addresses in a page.
*
* Change the $allowed value to the IP address you want.
*
* This works with drupal 4.5 and drupal 4.6
*/
$allowed  = '100.100.100.100';
$userip = $_SERVER ['REMOTE_ADDR'];
if(
$userip == $allowed){
    print
"This content can only be viewed by the IP address you specify.";
}
?>

To reverse the situation and HIDE content to a user from a specific IP address

<?php
/**
* this Snippet allows you to hide content from a visitor at
* a specific IP addresses.
*
* Change the $hidden value to the IP address you want.
*
* This works with drupal 4.5 and drupal 4.6
*/
$hidden  = ' 100.100.100.100' ;
$userip = $_SERVER['REMOTE_ADDR' ];
if(
$userip != $hidden){
    print
"This content is displayed to everyone except the person from the IP address you specify." ;
}
?>

Insert a quicklist of recent forum topic titles and links

PLEASE NOTE! The following snippets are user submitted. Use at your own risk! For users who have setup drupal using an alternate database to the default (MYSQL), please note that the snippets may contain some database queries specific to MYSQL.

<?php
/**
* Creates a quicklist of recent forum topic titles and a link to their
* node.
*
* works and tested with 4.6
* does not work with 4.5
*
* To increase the length of the list, change $listlength
*
*/
$listlength="10" ;
$sql = "SELECT n.nid, n.title, l.last_comment_timestamp, l.comment_count FROM {node} n INNER JOIN {node_comment_statistics} l ON n.nid = l.nid WHERE n.status = 1 AND n.type='forum' ORDER BY l.last_comment_timestamp DESC";
$sql = db_rewrite_sql($sql);
$content  = node_title_list (db_query_range($sql, 0 , $listlength), t('Active forum topics:'));
if (
$content) {
  
$content .= '<div class="more-link">' . l(t('more'), 'forum', array('title' => t('Read the latest forum topics.' ))) .'</div>';
}
print
$content;
?>

Insert an image before the promoted nodes on the frontpage

The front_page module allows for the display of a customized front page. This PHP snippet keeps the original front page (containing nodes promoted to the front page) and inserts an image (or other static content) in front of it.

Prerequisite: front_page module must be installed and configured properly.
Go to ADMINISTER - SETTINGS - FRONT_PAGE, check "Allow embedded PHP code" and enter the PHP snippet into the "Front page HTML" box.

<center><img src="my_image.gif"></center>

<?php
   
print node_page_default();
?>

Tested with drupal version 4.6.0.

Insert the most recent poll

PLEASE NOTE! The PHP snippets are user submitted. Use at your own risk! For users who have setup drupal using an alternate database to the default (MYSQL), please note that the snippets may contain some database queries specific to MYSQL.

<?php
/**
* the following displays the most recent poll
* and assumes you have the poll.module enabled
*
* Works with drupal 4.6
* Does not work with 4.5.x
*
*/
$sql = db_rewrite_sql( "SELECT MAX(n.created) FROM {node} n INNER JOIN {poll} p ON p.nid = n.nid WHERE n.status = 1 AND p.active = 1 AND n.moderate = 0");
      
$timestamp = db_result(db_query($sql ));
      if (
$timestamp) {
        
$poll = node_load (array('type' => 'poll', 'created' => $timestamp, 'moderate' => 0, 'status' => 1));
        if (
$poll->nid ) {
          
// poll_view() dumps the output into $poll->body.
          
poll_view( $poll, 1, 0, 1);
        }
      }
      print
$poll->body;
?>

maintenance redirect: automatically redirecting everyone but you away from the drupal site

PLEASE NOTE! The following snippet is user submitted. Use at your own risk! For users who have setup drupal using an alternate database to the default (MYSQL), please note that the snippets may contain some database queries specific to MYSQL.

<?php
/**
* This php snippet redirects everyone but you away from the drupal site
* to a htm page. Useful for "undergoing maintenance" type occasions
*
* put this snippet at the very top of your INDEX.PHP file in your root drupal folder
* or in your front_page settings page and place your closed.html
* file in the same folder.
*
* change the your_ip address to be your IP address so you can still access the site
*
*/
$your_ip = '100.100.0.1 ';
if (
$_SERVER['REMOTE_ADDR'] != $your_ip) {
  
header ('location:closed.html');
}
?>

Printing PHP variables from GET or POST forms

PLEASE NOTE These snippets are user submitted. Use at your own risk. For users who have setup drupal using an alternate database to the default (MYSQL), please note that the snippets may contain some database queries specific to MYSQL.

<?php
/**
* this Snippet illustrates how you display the values of a submitted form
* in a Drupal page.
*
* Submitted by puregin
*
* This works with drupal 4.5 and drupal 4.6
*/
print "variable1: " . $_POST["variable1"] ."<br/>";
print
"product: " . $_POST["product"] . "<br/>";
print
"size: " . $_POST[ "size"] ."<br/>";
?>

NOTES:

Change $_POST to $_GET if you used GET as your form method or if you are using a URL to set the variables. (e.g., example.com/page.php?variable1=hello )

Using more than one php snippet in the same node (or front_page)

In some circumstances, if you are using two or more php snippets in the same node - or on your front_page.module page - you need add the following line at the beginning of each php snippet you intend to use

<?php
unset ($output);
?>

why?

The reason is to avoid the problem of using the return $output; more than once in the same node. The return $output command will end the reading of code and all subsequent code or text in that node (or front_page) will be ignored.

To avoid potential problems, rather than return $output;, you can use...

<?php
print $output;
?>
...for the last line of code.

But...

With each subsequent php-generated list you create in that same node (or front_page), you will get a cumulative list -- the content generated by each additional php snippet will be added to the $output list. (For example, the second php snippet's list of posts on "apples" would be added to the first php snippet's list of posts on "oranges," when what you really want is just a list of posts on "apples.")

So how would one "clear" the output results so one can have another php snippet creating output? Start each of your subsequent snippets of php code with this:

<?php
unset ($output);
?>

This will clear the previous results so that your 2nd, 3rd ... nth list will have unique results relevant to its own query.

Thus you will be able to have several php-generated outputs on the same page (such as lists of recent posts in several different taxonomy terms) without conflict or intermingling of results.