Converting WordPress Category ID to Category Name - php

So, I'm working on a WordPress theme that uses a custom taxonomy to create a handy web form.
Right now it prints Grandparent and child, but I need it to print:
Grandparent -> Parent -> Child
I've been been able to get the ID of the Parent, but cannot print that parent's name, no matter what I try.
Here's what I have to get the id:
$adCategory = get_term_by('id',$_POST['cat'],'ad_cat');
$_POST['catname'] = $adCategory->name;
$mainCategory = get_term_by('id',$_POST['main_cat'],'ad_cat');
$mainCat = $mainCategory->name;
$categoryParent = get_term_by('id',$_POST['cat'],'ad_cat');
$catParents = $categoryParent->parent;
(first group prints child, second prints grandparent, third prints id
and here is how I'm able to print them all on the page:
<?php echo $catParents; ?>
<?php echo $mainCat; ?>
<?php echo $_POST['catname']; ?>
I've tried get_cat_name, but it won't work, just returns empty. Any ideas?

If you already have an ID you can at least make a direct query
$wpdb->get_var('SELECT name FROM '.$wpdb->terms.' WHERE term_id = '.$term_ID);

Related

Getting first & last post in custom post type outside of loop

I'm using WP, and have a script where when an image is clicked, the single post content loads using .load(). The arrows to navigate through each single post is located inside the .project div that is being loaded using .load().
Problem is, on the first and last posts, I only want to display certain arrows.
For example, the first item in the post gets loaded in, it shouldn't have the 'previous' arrow because there are no previous posts. Same with the last post and the 'next' arrow.
So basically to work around this, I'm trying to come up with a PHP statement (without being in the loop) to tell if the current post is the last post or first post in the custom post type.
Here's what I have so far.. just not sure how to get ID's of first post and last post outside of the loop. Everything else besides that has been tested and works. Below is just the 'logic' behind the code mostly.
<?php
// Get other posts in post type
$next_post = get_next_post();
$previous_post = get_previous_post();
$current_id = get_the_ID();
// Get ID's of posts
$next_id = $next_post->ID;
$previous_id = $previous_post->ID;
// if($next_id == $previous_id) because on first/last posts, get_next_post
// and get_previous_post return the same value.
if($next_id == $previous_id) {
if() {
// if last post in custom post type
} else() {
// if first post in custom post type
}
}
?>
<?php if(isnt first post) { ?>
<li class="left" data-projectid="<?php echo $next_id; ?>"></li>
<?php } ?>
<li class="grid"></li>
<?php if(isnt last post) { ?>
<li class="right" data-projectid="<?php echo $previous_id; ?>"></li>
<?php } ?>
I haven't worked with WP so much, but since WP templates are all PHP files and WP exposes its own API to user you can use any PHP syntax in them. If you're not concerned about running two queries each time you navigate your page then this will help you to get the idea.
<?php
global $wpdb;
$last_one = FALSE;
$first_one = FALSE;
// Get last one
$last_result = $wpdb->get_results("SELECT `id` FROM `posts` ORDER BY `id` DESC LIMIT 0, 1", ARRAY_A);
if($last_result){ if($last_result['id'] == $next_post){ $last_one = TRUE; } }
// Get first one
$first_result = $wpdb->get_results("SELECT `id` FROM `posts` ORDER BY `id` ASC LIMIT 0, 1", ARRAY_A);
if($first_result){ if($first_result['id'] == $previous_post){ $first_one = TRUE; } }
?>
Remember to check the names of fields and tables as I don't know the names.
Ended up using this code and it works fine...
Edit: updated code.. if for any reason somebody else ever needs it:
$args = array('post_type'=>'your_post_type', 'posts_per_page' => -1);
$posts = get_posts($args);
$first_id = $posts[0]->ID; // To get ID of first post in custom post type
// outside of loop
$last_id = end($posts);
echo $last_id->ID; // To get ID of last post in custom post type outside of loop
if($current_id != $first_id) { ?>
<li class="left" data-projectid="<?php echo $previous_id; ?>"></li>
<?php } ?>
<?php if($current_id != $last_id->ID) { ?>
<li class="right" data-projectid="<?php echo $next_id; ?>"></li>
<?php } ?>

magento getpath() extract value

I would like to request information of how to extract a particular value in getpath() function.
currently I placed the following information:
<?php $currentCat = Mage::registry('current_category'); ?>
<?php echo $currentCat->getPath()?>
and the system echo 1/2/5 , where 1 is root of root, 2 is catalog root and 5 is the first simple category.
I would like to extract the third value only (number 5 in this example) in that serie of categories to echo that info only in the page but i tried different appraches with no success.
thank you.
explode(), end()
<?php echo end(explode("/", $currentCat->getPath())); ?>
do you know if I can place a value to retrieve always that 3 level no matter if im placed in another subcategory
Should looks like this:
<?php
$exp = explode("/", $currentCat->getPath());
echo $exp[2];
?>
I would recommend you to take a look at explode() again :)

PHP Menu - Loading from Database, can't get structure right

I'm having a hard time getting this menu to work properly.
function writeMenu(){
echo "<div id=\"menu\">" <ul id=\"top-link\">";
m("top", "n"); echo "</ul></div>"; (sorry, it wouldn't format properly)
function m($parent,$issub){
$parentQ = "select * from cdi_menu";//gets menu items from menu table
$parentResult = mysql_query($parentQ); //runs menu item query and obtains result
while ($link = mysql_fetch_assoc($parentResult)) {//for each line in the result do the folowing:
if($parent==$link['PARENT']){//if the next link belongs to this menu item
echo "\n <li>".$link['DISPLAY']."</li>";
if($issub=="n" && $link['HASCHILD']=="y"){//if this menu item is a top menu item
echo "\n <li id=\"sub-link\"><ul>";
m($link['ID'], $links, "y");
echo "\n </ul></li>";
}
}
}
}
echo writeMenu();
What I'm trying to do is make it where I can hide the 'sub-link' IDs (I would use classes, but javascript doesn't seem to edit class styles, just IDs). The sub-link items would show when over a parent item.
top refers to the top elements, and ID refers to the unique id in database.
Thanks, sorry if it's confusing.
Your function has only 2 parameters but You call it with 3 inside
m($link['ID'], $links, "y");
$links is unnecessary.
It would be better if You modify query to look like this
$parentQ = "select * from cdi_menu WHERE parent='$parent'";
so You don't need first if statement and You will not fetching all rows multiple times for each menu/submenu.

How to create a mysql php multi-level list navigation

Basically I want to be able to create a multi-level navigation (many sub navs). Obviously I know this will be done through creating lists with in each other but I am pretty stuck on the logic of displaying it correctly.
I have seen stuff regarding parent/children relationships but can't find anything that is efficient and easy to udnerstand.
I don't need to know how the HTML is built. Just how the php/mysql can generate the lists.
Hope you can help.
A
Here is code I used. It builds unordered list with unlimited level of subitems.
/*
* Table has 3 fields: `ID`, `PARENTID` and `NAME`
* `ID` is unique, `PARENTID` showing his parent node id.
* This function will go through it and build unordered list and call itself when needed to build subitems.
* $level argument used to define wich node's subitems to build. Default is 0 which is top level.
*/
function showMenu($level = 0) {
$result = mysql_query("SELECT * FROM `tbl_structure` WHERE `PARENTID` = ".$level);
echo "<ul>";
while ($node = mysql_fetch_array($result)) {
echo "<li>".$node['NAME'];
$hasChild = mysql_fetch_array(mysql_query("SELECT * FROM `tbl_structure` WHERE `PARENTID` = ".$node['ID'])) != null;
IF ($hasChild) {
showMenu($node['ID']);
}
echo "</li>";
}
echo "</ul>";
}
Hope that helps.
I think the most efficient would be to get all records in one go from the database and then build the hierarchical structure again in php.
So you would have a structure similar to this in your database:
id parent_id menu_item
Then you can get all items and use a recursive function to build a hierarchical array which you can loop through to get your menu, sub-menu, sub-sub-menu, etc. items. See this question and the top-two answers on how to re-build the structure.
If you mean the HTML it's like this:
<ul>
<li>
Title
<ul>
<li>Title</li>
<li>Title</li>
<li>Title</li>
</ul>
</li>
<li>Title</li>
<li>Title</li>
<li>Title</li>
</ul>
assuming you know how to create filled with the content of a mysql table
assuming you have the following tables : Universes > Categories > Markets > Segments
1) list the content of 'Universes' in a select. when the user picks, call another .php script and send it the id of the chosen Universe (using GET or POST)
2) list the content of 'Categories', WHERE idUniverses = the id you sent to the second script.
3) same for the Markets...
It's easier with AJAX.
need the code ?

PHP echo variable within function arguments

I'm currently using a wordpress function in order to display posts from a specific category. A simplified example is shown below:
<?php query('cat_name=cat1&posts=1') ?>
Essentially this gets 1 post from the category cat1.
However I have a variable saved which gets the current category (this is on category pages):
<?php $thiscat = get_the_category(); ?>
Current Category: <?php echo $thiscat ?>
How can I now echo the variable $thiscat into the arguments of my query above so that the category name is filled in for me? This function is applied on different category pages so having it automatically passed to the arguments of my query saves a lot of hassle.
Thanks in advance for any help.
You only echo something when you want to output it to the browser, here we concatenate the query string with the variable:
<?php $thiscat = get_the_category(); ?>
<?php query('cat_name=' . $thiscat . '&posts=1') ?>
Not sure I understand the question, but it sounds like you want to use $thiscat in your query. This should do it:
<?php
$thiscat = get_the_category();
query("cat_name=$thiscat&posts=1")
?>
Note the double quotes, which are necessary. If you use single quotes, the variable will not get expanded.

Categories