Grabbing Category Names

While creating my Galleries section, I discovered that I needed to be able to display the name of the current category (which I am using to essentially group “photo albums”).  I started with a small hack that Rick posted in the pMachine forums.  However, I wanted it to be more dynamic so that I didn’t have to create a bunch of if-else statements as his required.

Updated: This entry was updated October 3, 2003.  Changes made allow it to be used with SE-friendly URLs as well as make it more flexible in more situations.  This was tested on pM v2.3, and I don’t know how well it will work on previous versions.

Multi-Entry Page

So, I modified Rick’s code to include a database query.  The query grabs the category name based on the category ID that is extracted from the $id variable.  Here is the code snippet for it.  You’d place this immediately after the <?php include(“pm_inc.php”); ?> tag.

<?php

  // If the user selects "View All", display this text:
  $catname = "All categories";


  // Check to see if the $id is for a category
  if (substr($id, 0,1) == "C") {
// Get the category ID
$x = explode("_",$id);
$cat_id = $x[1];

$db = new DB();

// Query the database to return the category
// name based on the ID
$sql = "SELECT category " .
"FROM $db_categories " .
"WHERE id=$cat_id";
$result = mysql_query($sql);

// Store the category name in $catname
list($catname) = mysql_fetch_row($result);

mysql_free_result($result);

}  // END LEAVE THIS
?>

I used this tag on the “galleries.php” page for my Galleries because it will only ever be accessed via categories.  You can see the dynamic elements in the <title> as well as at the top of the page.

Single-Entry Page

Note: If you just want to display the category name on the page, then it will almost certainly be easier to use the standard

<?php show_field($id,"category"); ?>

tag.  What this hack is useful for is being able to grab the category name so that you can use it as a variable and pass it to other functions/tags.

I then needed to be able to do the same thing on the single-entry (individual) page associated with the weblog.  The $id variable is structured differently here, however, so it required a slightly different approach:

<?php

  $catname = "";

  $postid = get_id($id, 1);

  $db = new DB();

  // Using the entry ID, grab the associated category ID
  $sql = "SELECT category " .
        "FROM $db_weblog " .
        "WHERE post_id=$postid";

  $result = mysql_query($sql);

  // Store the category name in $cat_id
  list($cat_id) = mysql_fetch_row($result);

  mysql_free_result($result);


  // Query the database to return the category
  //  name based on the ID
  $sql = "SELECT category " .
        "FROM $db_categories " .
        "WHERE id=$cat_id";

  $result = mysql_query($sql);

  // Store the category name in $catname
  list($catname) = mysql_fetch_row($result);

  mysql_free_result($result);

  }  // END LEAVE THIS
?>

This version is used on the page that displays when you click on a thumbnail image.  Again, you can see the dynamic elements in the <title> as well as at the top of the page.

Using the Variable

In both cases, the category name is then accessible through the $catname variable.  For instance, wherever you want it to appear on the page, you can just use:

<?php echo $catname; ?>

This is an older entry and as such, it may be by a guest author or contain formatting problems / extraneous code. If you notice something wrong with the entry, please use the Contact page to let me know the entry title and issue.

Comments

Hi Chris

I do not understand the idea with grabbing the categories name and where to put it

Or my brain can’t follow it grin

I did this in my photolog template

Weblog Multi-entry Templates (photo2)
Weblog - Master Date Heading (photo2)

TAG: <?php weblog_entries($id,“photo2”); ?>

<h3><b>Galleri: </b>%Ętegory%%</h3>

Then it shows the cagory name.

By the way is there a way to get the image title automaticly with the picture. You know when the mouse is over the picture it shows the alt=“image” so i don´t have to manually to write it.

Nic

This trick is so that you can display the category outside of the pM templates.  For instance, I use it on my pages inside the <title></title> tag, among other places.  It’s also conditional in that nothing will be displayed if you aren’t accessing something through a category link.

> By the way is there a way to get the image title automaticly with the picture.

That completely depends on how you have your weblog and templates set up.

Okay - thx

On wich pages are you putting the grabbing thing?

That I can’t follow

I’m using the “Multi-Entry” version on galleries.php.  “Backpacking (Dec 1997)” is the category name and you’ll see that I use it in the <title></title> as well as at the top of the page.  If you go to one of the other galleries, you can see how that part of the page changes automatically to reflect the current category.

Once you’re in a gallery, click on a thumbnail.  The page that loads in the pop-up is where I use the “Single-Entry” version.  Again, I use the category name in the title and at the top of the page and it will change depending on the current category.

(I’m also using the trick on the new “Movie Database” page as well.)

Hi Chris

Now I started all over with exactly your guide, but I can’t get it to work with grabbing the categories name.

The galleries link: http://thebign.dk/galleries

In the page galleries.php with the first code:

<?php include(“pm_inc.php”);?>
<?php

// Check to see if the $id is for a category
if (substr($id, 0,1) == “C”) {
// Get the category ID
$x = explode(“_”,$id);
$cat_id = $x[’1’];

and the rest…..

The next page view.php

<?php include(“pm_inc.php”);?>
<?php

// Grab the last part of the $id
$x = explode(“_”,$id);
$last = $x[(count($x)-1)];

and the rest…

At last I placed the tag:
<?php echo $catname; ?>

In both pages - And nothings is happening.

Hmmmm?

Here is link for all the files as zip

http://thebign.dk/galleries/galleries.zip

Nic

Hi Chris

Now it works on view.php page

How I don’t know, now there is only the galleries.php page left

Nic

Open up galleries.php.  Toward the top, you’ll see the line:

$cat_id = $x[’1’];

Make sure you have regular “single-quotes” around the 1.  It looks to me like pMachine may have put in special quotes there when it displayed my code.

Yeah

Thanks a lot, now it works.

Nic

Thanks for the great hack, which I looking for long long time. Great work. Thanks again.

Hi Chris

I have now finished my galleri with your toturial guide.

I made a link to your homepage in the the galleri. I have written that the galleri is made with your guide.

The galleri link: http://thebign.dk/galleries

Thanks a lot for your support.

Take care And Have Fun

Nic

Hello Chris,

I’m trying to implement your category grabbing script, but I don’t get it to show the category name.

I put the following code at the top of my page:

<?php include(“pm_inc.php”); ?>
<?php

// Check to see if the $id is for a category
if (substr($id, 0,1) == “C”) {
// Get the category ID
$x = explode(“_”,$id);
$cat_id = $x[’1’];

$db = new DB();

// Query the database to return the category
// name based on the ID
$sql = “SELECT category ” .
“FROM $db_categories ” .
“WHERE id=$cat_id”;

$result = mysql_query($sql);

// Store the category name in $catname
list($catname) = mysql_fetch_row($result);

mysql_free_result($result);

} // END LEAVE THIS
?>


The page in question is at: http://mmjaeger.com/community/links/links.php?id=C0_39_10.

Do you have any idea what could be the problem.

Thank you in advance for your help.

Read comment above, by Chris Curtis @ 01/05/03 10:27pm

mmjaeger,

As Gabriel suggested, check my comment above.  Also, did you put the display code anywhere in your page?
<?php echo $catname; ?> 

Hello Chris,

I noticed a problem with the single entry category grabbing script!

Let’s say, I’m on a single page with the prev and next link. When I’m entering the single entry page the category name is shown correctly. When I’m clicking on e.g. the next link, it is o.k. as well until I get a picture from another category. It still keeps the old category name then.

Just wanted to let you know about this.

I don’t quite understand why you’re using the list() function when there’s only one result involved?  In both cases there will always only be one result.

I’m interested in the reasoning behind this.  I would (and actually did when I setup my photolog over the summer) set it up replacing:

list($catname) = mysql_fetch_row($result);

with:

$row = @mysql_fetch_array($result);
$catname = stripslashes($row[‘category’]);

I’m just interested in why you chose to use the list function. smile

No particular reason, Lynda.  Mostly, I suppose it’s that I’ve gotten used to using that method and it’s just what I used automatically without really even thinking about it.

I don’t think there’s any real advantage to either approach since they’re both just grabbing a value from an array.

I’ve never seen the list() function used in that context before which was why I was asking.  It does cut the amount of code down by one line.  I’m always interested in learning something new. smile

Hello chris,

How are you today?

I just discovered a little problem with the grabbing category name on a single-view page.

I’ve limited the number of comments that are shown on the single-view page.

Clicking on the NEXTpage link, the category info is lost, so the category name is not shown anymore on the page.

Any ideas how to fix this.

Thank you

I don’t think there’s anything you can do apart from hack the backend comment display file.  There’s simply no way to pass along the category information otherwise.

This trick wasn’t ever meant to work in all cicumstances.  It worked for what I needed, but it would be impossible to anticipate all the ways other people might implement it.

Well, if the entry ID is passed along, you can always get the category information.  Just do a query using the post ID to grab the category number and then another one using the number to get the name.

Yeah, you’re right, Lynda.  My brain’s been really loopy lately, so that didn’t even occur to me.  Basically, you’d have to do an if-else.

If the category info is passed in the entry id, then use what I have normally, otherwise you’ll have to do the queries that Lynda suggests.

Hi Chris,
I’m using the catname variable and it works well but on the View All page it throws error.  Ideas?

You’d probably need to put an if-else conditional around the <?php echo $catname; ?> so that it only showed if it were not a “view all”.

You could also put the conditional earlier in the script, but that’s a bit more difficult.

I’m Php illiterate could you give an example of the if-else statement

Thanks

The simplest solution would simply be to add this at the top of each of the PHP chunks (i.e. after the <?php and before the code to get the information):

$catname = “All categories”;

Replace the text as you want or even simply have it as $catname = “”;

It works, thanks once again!!

Hi, the multy-entry snippet works, but for single-entry it doesn’t, i think it has something to do that the url’s on the site i’m testing have id’s like that :

id=37_0_8_0_M

(without the usual C), do you have any idea on how to change/repair that?

Regards.

Hey Chris,

Thanks for this. worked like a charm. i added an echo inside the if statement and ran it inline, works perfect.

Chris,

I moved my blog to another server, and now I am getting an error message

Notice: Undefined variable: catname in /home/gladman/public_html/blog/gfd.php on line 200

any ideas?

Tim, take a look at one of my previous comments - specifically, the comments made on 02/25/03.

problem was debug was on.

I’m getting “Fatal error:  Cannot instantiate non-existent class:  db”

Does this hack only work with certain versions of pMachine?  I am on the free 2.1 version.

I was made this code:

<img src=“NASLOVI/
<?php
echo $catname=preg_replace(’/<!—.+?—>/’,’‘,$catname);
?>
.gif” />

it works fine, but something picture not load. when i see the properties of that picture it is /NASLOVI/.gif

when I refresh page picture is loaded.. WHY!? somebody can explain this paradox!?

No, but I can explain to you what paradox means.  “A seemingly contradictory statement that may nonetheless be true.”  Or an assertion that is apparent to be contradictory.  For instance, when someone says that “standing or driving in a car is more tiring that walking all day.”

smile Thank you, but thats not think which intrested me so much.

:beer:  Thanks Chris, another great bit of php from you for us php as a second language folks.

Just wanted to let you know that I implemented your code snippet and it works fine.

Solved a problem I had been sweating over for some time. For some reason the %Ętegory%% variable would not display the category name if I inserted it in my multi-entry or headlines templates.

many thanks

Chris

Greetings from Malaga (Spain). Antonio grin

Leave Your Comment

Comments may be edited for content or deleted at any time. Civilized discussion is welcome. Anyone spamming, going way off topic, or otherwise being a jerk will probably be deleted or banned.

User Information

pMcode is allowed for comment formatting. pop-up mini reference

Personalization Options

Comment Security