R
R
Rasul Gitinov2016-03-03 01:19:32
PHP
Rasul Gitinov, 2016-03-03 01:19:32

How to make a function work on a specific page?

I have a function that displays the subcategories on the category page, but the problem is that it works on the main page as well and displays the categories mixed with the subcategories. Here is the code:

$i=1;
$cat = get_query_var('cat');
$categories = get_categories('parent='.$cat.''); 
foreach ($categories as $category) { $i++; }
if ($i > 1) {
  echo "<ul>";
  foreach ($categories as $category) { ?>
    <li><a href="<?php echo get_category_link($category->term_id); ?>" ><?php echo $category->name; ?></a></li>
  <?php } 
  echo "</ul>";
} else {
  $pcat = get_category(get_query_var('cat'),false);
  $pcatid = $pcat->category_parent;
  $categories = get_categories('parent='.$pcatid.''); 
  echo "<ul>";
  foreach ($categories as $category) { ?>
    <li<?php if ($category->term_id == $cat) { ?> class="active"<?php } ?>><a href="<?php echo get_category_link($category->term_id); ?>" ><?php echo $category->name; ?></a></li>
  <?php } 
  echo "</ul>";
}

I put it in the index.php file, but I need it to work only in the category page, and not on the main one.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rasul Gitinov, 2016-03-03
@raselgit

I created a category.php file and inserted all the code from index.php into it along with my function, and removed it from index.php and everything worked.

C
Cyber_bober, 2016-03-03
@Cyber_bober

put it on the category page?! Of course, you can play around with the url definition or load the script in php if !==home

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question