Skip to content

Instantly share code, notes, and snippets.

@millerda
Last active August 29, 2015 14:01
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save millerda/a48907eae6bf26c818b0 to your computer and use it in GitHub Desktop.
Simple function used to pull post titles and embed links to those titles in a sidebar of a page.
<?php
function pullTitle($text) {
$startsAt = strpos($text, "<h2>") + strlen("<h2>");
$endsAt = strpos($text, "</h2>", $startsAt);
$result = substr($text, $startsAt, $endsAt - $startsAt);
return $result;
}
function pickSection($dir) {
if(strpos($dir,"tech")) {
$section = "tech";
}
elseif (strpos($dir,"blog")) {
$section = "blog";
}
else {
$section = "musings";
}
return $section;
}
function makeSidebar($dir, $numPosts) {
# get the proper section
$section = pickSection($dir);
$filearray = array_diff(scandir($dir,1), array('..', '.'));
# 0 means that all posts should be added
if($numPosts == 0)
{
# write the opening part
echo "
<div class=\"col-md-4 col-sm-4\">
<div class=\"container-fluid sidebar not-fixed\">
<h4>Older posts</h4>
<div class=\"list-group\">
";
# iterate through the proper number of files
for($i=1; $i<count($filearray); $i++){
if($i == count($filearray)){
break;
}
else{
# pull the file extension off and store in new variable
$filearray[$i] = preg_replace("/\.[^.]+$/", "", $filearray[$i]);
# pull the file contents
$title = file_get_contents($dir . "/" . $filearray[$i] . ".php",false,NULL,0,200);
# and get the title from the html
$title = pullTitle($title);
# print out the appropriate HTML
echo "<a href=\"./archive-$section.php#$filearray[$i]\"
class=\"list-group-item nav-side\">$title</a>";
}
}
echo "
</div>
</div>
</div>
";
}
else{
# write the opening part
echo "
<div class=\"col-md-4 col-sm-4\">
<div class=\"container-fluid sidebar\">
<h4>Older posts</h4>
<div class=\"list-group\">
<a href=\"./archive-$section.php\" class=\"list-group-item nav-side\">
All archived posts</a>
<hr></hr>
";
# iterate through the proper number of files
for($i=1; $i<$numPosts; $i++){
if($i == count($filearray)){
break;
}
else{
# pull the file extension off and store in new variable
$filearray[$i] = preg_replace("/\.[^.]+$/", "", $filearray[$i]);
# pull the file contents
$title = file_get_contents($dir . "/" . $filearray[$i] . ".php",false,NULL,0,200);
# and get the title from the html
$title = pullTitle($title);
# print out the appropriate HTML
echo "<a href=\"./archive-$section.php#$filearray[$i]\"
class=\"list-group-item nav-side\">$title</a>";
}
}
echo "
</div>
</div>
</div>
";
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment