Php syntax for echoing multiple classes with a space between them - php

I'm am working on a Wordpress custom template and I'm filtering post by their classes.
Since Wordpress displays a LOT of unnecessary classes when I put <?php post_class(); ?> in a page, ( here is what it gives me class="post-54 post type-post status-publish format-standard hentry category-3d category-web" )
I'm trying to simplify that by echoing only the categories that relate to the post.
EDIT: This is what calls the post in my page <?php query_posts( 'showposts=99' ); ?>
Then this piece of code
<li class="<?php if ( in_category('category-3d')) { echo "3d"; }
if ( in_category('category-animation')) { echo "animation"; }
if ( in_category('category-motion')) { echo "motion"; }
if ( in_category('category-shortfilm')) { echo "shortfilm"; }?>"></li>
give me this <li class="motion"></li> if my post is in the "motion" category.
The problem is that if my post is in several categories, only the first is echoed... How can I tell WP to echo ALL the names of the categories my post is affected to, while adding a space between them?
Since I am a beginner in php syntax, I'm still learning how to get such a simple thing working in a clean and effective way (i.e. without writing 16 lines of code !)...
Can someone help me on this one?
SECOND EDIT:
Ok I'm still trying to figure out why, but today, my piece of code (above) is working and echoes all my listed classes, but without space between them... So to make my classes work, I'm adding a space at the end of the echo part like this { echo "3d "; }. But I feel like it's a dirty way to make things work...
How to add a space between each class tag in the proper way? I'm aiming for something like this foreach $categories as $cat { echo $cat . " "; } but where $categories and $cat would refer to each "if" statement.

I'm not familiar with WP but if you get your categories with some function like get_categories() then you can use implode to make a string from all categories.
<?php $categories = get_categories(); ?>
<?php $categories = implode(' ', $categories); ?>
<li class="<?php echo $categories; ?>">...</li>
Could you provide what is returning get_categories()?
EDIT:
function get_class_attr() {
$classes = get_post_class();
$classes = substr($classes, 7, -1);
$arr = array();
$arr = explode(' ', $classes);
$classes = 'class="';
foreach($arr as $class_name) {
if(strpos($class_name, 'category-') !== false) {
$classes .= substr($class_name, 9).' ';
}
}
$classes = substr_replace($classes, '"', -1, 1);
echo $classes;
}
get_class_attr(); // output: class="3d web"
Also note that 3d is not a valid class name, you can use something like movie3d or film3d.
Alternative way is to create your class value a little bit earlier and then echo it:
<?php
$classes = array();
if ( in_category('category-3d')) { $classes[] = "3d"; }
if ( in_category('category-animation')) { $classes[] = "animation"; }
if ( in_category('category-motion')) { $classes[] = "motion"; }
if ( in_category('category-shortfilm')) { $classes[] = "shortfilm";}
if(count($classes)) {
$classes = implode(' ', $classes);
} else {
$classes = '';
}
?>
<li class="<?php $classes ?>"></li>

As of the code you've posted, it should add all the categories if the product is in all the four specified ones. You could add the space between the quotes after each echo, e.g.: echo ' motion'.
I would use another approach, adding really all categories, without the need to check them by name:
<li class="<?php echo implode( ' ', get_categories() ); ?>"> … </li>
See: http://codex.wordpress.org/Function_Reference/get_categories on how to filter the output of the function get_categories().

I would suggest instead you use this function from the Wordpress API - something you should read a lot of.
Something like this should work:
<?php $categories = get_categories(); ?>
<li class="<?php foreach ($categories as $cat) {
echo $cat . " ";
}?>"> -- Your li text --
</li>

Related

Combine two PHP variables into one if one variable is not empty

So this is a zany thing that I'm attempting to do, but what I am trying to achieve is querying out some info in WordPress with categories. If a post comes back with a parent category, then echo that out with the child category with a | seperator. If no parent category then just echo out the category.
Here's what I'm trying so far:
<?php
$categories = get_the_category();
$catName = $categories[0]->name;
$catParent = get_cat_name($categories[0]->category_parent);
if($catParent) {
$fullCat = $catParent '|' $catName;
} else {
$fullCat = $catName;
echo $fullCat;
?>
I know this is incorrect, but basically, I'm trying to wrap my head around how to accomplish this. I'm not sure how to combine two variables to use one and then add the separator within the two.
Was also wondering if maybe a ternary operator might be better here too? That was more of thought than anything and probably not that necessary to make this work correctly.
You're wanting to check if $catParent is empty so you can use the empty() function to do that check for you. Quick edit...you need periods (.) in between things you are concatenating.
Link to the docs.
if(empty($catParent)) {
$fullCat = $catParent . '|' . $catName;
} else {
$fullCat = $catName;
}
You must use '.' to concat.
Example:
$fullCat = $catParent. ' | '. $catName;
You can use . (Concatenation) operator to achieve this. Look at the code below.
<?php
$categories = get_the_category();
$catName = $categories[0]->name;
$catParent = get_cat_name($categories[0]->category_parent);
if($catParent) {
$fullCat = $catParent . '|' . $catName;
} else {
$fullCat = $catName;
echo $fullCat;
?>

How to get all tags from Wordpress page/post as a list in shortcode?

At the end of each page and every post, I would like to output the tags as a list in a shortcode.
Unfortunately, I do not know much about PHP, but someone who can understand will definitely be able to correct my mistake using the code below.
Thank you in advance!
<?php // functions.php | get tags
function addTag( $classes = '' ) {
if( is_page() ) {
$tags = get_the_tags(); // tags
if(!empty($tags))
{
foreach( $tags as $tag ) {
$tagOutput[] = '<li>' . $tag->name . '</li>';
}
}
}
return $tags;
}
add_shortcode('tags', 'addTag');
The method needs to return a string to be able to print any markup.
"Shortcode functions should return the text that is to be used to replace the shortcode." https://codex.wordpress.org/Function_Reference/add_shortcode
function getTagList($classes = '') {
global $post;
$tags = get_the_tags($post->ID);
$tagOutput = [];
if (!empty($tags)) {
array_push($tagOutput, '<ul class="tag-list '.$classes.'">');
foreach($tags as $tag) {
array_push($tagOutput, '<li>'.$tag->name.'</li>');
}
array_push($tagOutput, '</ul>');
}
return implode('', $tagOutput);
}
add_shortcode('tagsList', 'getTagList');
Edit: Removed check for is_page since get_the_tags will simply return empty if there aren't any
Be aware that pages don't have tags unless you've changed something.
That said, this should work. It also adds the <ul> around the tags, but you can change that, and I'm sure you see where. I've used is_singular, but you'll probably get away without that condition at all, unless you do add [tags] in a custom post type and don't want the output there.
I assume you want to add more modification, otherwise webdevdani's suggestion regarding using the_tags is probably simpler.
// get tags
function addTag( $classes = '' ) {
if( is_singular("post") || is_singular("page") ) {
$tags = get_the_tags();
if(is_array($tags) && !empty($tags)) {
$tagOutput = array("<ul>");
foreach( $tags as $tag ) {
$tagOutput[] = '<li>' . $tag->name . '</li>';
}
$tagOutput[] = "</ul>";
return implode("", $tagOutput);
}
}
return "";
}
add_shortcode('tags', 'addTag');

Remove all links from categories

I have listed all the post categories in my WordPress slider. But there's a problem; the category names are links.
if(has_category()) {
$cats_list = get_the_category_list(', ');
} else {
$cats_list = 'No categories';
}
And it's outputted by this:
<?php echo $cats_list; ?>
Is there any way to remove the links around it? I've read the WP docs but they don't give me any info about the links.
Solved it by creating this:
foreach((get_the_category()) as $category) {
echo $category->cat_name . ' ';
}
That still needs some tweaks, though.
A response from this question could help you:
$categories = array()
foreach((get_the_category()) as $category) {
$categories[] = $category->cat_name;
}
echo implode( ', ', $categories );
You could also change your echo line to:
<?php echo strip_tags($cats_list); ?>
Hope it helps!

PHP Code efficiency in menu

I currently have some VERY long winded code for the menu I use on my site.
My website
It's almost 2000 lines long lol. I think I may be able to use a switch but I've tried and cannot implement it to work properly.
On each menu when you click a button it stays highlighted, telling the user that they are on that page. The only way I could get this to work was like so...
if($subject == 'art') {
echo '<div id="spacer2"><br></div>';
echo '<div class="idName2" id="menu2">';
echo 'All';
echo '<div id="spacer2"><br></div>';
echo '</div>';
echo '<div class="idName3" id="menu3">';
echo 'Art';
echo '</div>';
echo '<div class="idName2" id="menu2">';
echo 'Biology';
echo 'English';
echo 'Chemistry';
echo 'Mathematics';
echo 'History';
echo 'Religion';
echo 'Geography';
echo 'Music';
echo 'Philosophy';
echo 'Psychology';
echo 'Economics';
echo 'Sociology';
echo 'Technology';
echo 'Electronics';
echo 'Food';
echo 'Law';
echo 'Politics';
echo '</div>';
}
elseif($subject == 'biology') {
and then there's however many 'elseifs' as there are menu items, which ends up totalling to 2000 lines of code which is obviously very inefficient and it also makes it unbelievably time consuming to change anything... can someone point me in the right direction in what I need to do please!
Navigation is always a pain. Here is a simple solution that might help.
Put everything in an array, like this:
$menu = array(
'All' => '/browse ...',
'Art' => '/browse ... art',
'Biology' => '/browse ... biology',
// etc.
)
Then, you can build all the links based on the current subject:
$subject = 'Art';
foreach ($menu as $title => $url) {
if ($title == $subject) {
echo "<b>$title</b><br>\n";
} else {
echo "$title<br>\n";
}
}
This is a rather simplistic solution, but it can be extended to create a more complicated menus structure.
Another solution you could look at is Zend_Navigation.
http://framework.zend.com/manual/en/zend.navigation.introduction.html
What about something like:
$subjects = array('art', 'biology', 'english', 'chemistry' /*, etc */);
foreach ($subjects as $current_subject)
{
if ($current_subject == $subject)
{
//write it the id="menu3" way
}
else
{
//write it another way
}
}
You can transform 'biology' to 'Biology' using the ucfirst function.
Also note that there can't be two or more elements with the same ID (menu2 in your case).
You should use an array to represent your menus. Even better, you could place it in a resource file (xml would be preferable), but explaining that exceeds the scope of this answer (nonetheless, you should look into it). Using an external resource for the menu has the added benefit that you can change your menu structure without modifying any code.
Sticking to the simple approach, this is how you should represent your menu without an external resource:
$menus = array('Art', 'Biology', 'English', ...);
You can generate the "A"-"Z" submenus with a simple range command: range('A', 'Z')
So your code echoing the menus would be something like:
<?php
$current_letter = $_REQUEST['letter'];
$current_menu = $_REQUEST['menu'];
$letters = range('A', 'Z');
foreach($letters as $letter) :
$class = $current_letter == $letter ? 'class="active"' : '';
?>
<a <?php echo $class; ?> href="browse.php?letter=<?php echo $letter; ?>&menu=<?php echo $current_menu; ?>&listtype=<?php echo $listtype"><?php echo $letter; ?></a>
<?php endforeach; ?>
This displays the top menubar (A-Z links). For the side menu, here is how to display your categories:
<?php
foreach($menus as $menu) :
$class = $current_menu == $menu ? 'class="active"' : '';
?>
<a <?php echo $class; ?> href="browse.php?letter=<?php echo $current_letter; ?>&menu=<?php echo $menu; ?>&listtype=<?php echo $listtype"><?php echo $menu; ?></a>
<?php endforeach; ?>
Haven'tested it, but apart from possible typos this approach should work for you.
Btw, please don't throw things at me for not validating input and using $_REQUEST directly. It should be done, but that is a whole other topic.

How do I nest a wordpress function inside another wordpress function?

I'm working on a wordpress theme and I'm trying to call the parent category's name to pull the appropriate page template.
I can get the call function to echo the correct name, but when I try to nest it the function doesn't run. I saw that I needed to use { } since I was already inside php but it still isn't working right. Can someone straighten me out?
This gives the correct output:
<?php $category = get_the_category();
$parent = get_cat_name($category[0]->category_parent);
if (!empty($parent)) {
echo '' . $parent;
} else {
echo '' . $category[0]->cat_name;
}
?>
. . . so I created a category_parent.php file with that in it.
This is what I'm trying to nest it in:
<?php get_template_part( ' ' ); ?>
Like this:
1.
<?php get_template_part( '<?php get_template_part( 'category_parent' ); ?>' ); ?>
or this
2.
<?php get_template_part( '{get_template_part( 'category_parent' ); }' ); ?>
Neither one works.
I really don't know if this is what you want as I did not try to make sense of what you are doing. However, generally speaking, you do this:
<?php get_template_part( get_template_part( 'category_parent' ) ); ?>
Edit:
I looked up what get_template_part() does in WP, and I think Felix Kling's answer is what you need. There is a big difference between sending something to the screen and assigning it to a variable.
<?php
echo 'filename';
?>
If you include that file, you will see filename in the browser. PHP knows nothing about it. (Okay, it could if you made use of output buffering functions, but that's besides the point...)
However if you do something like:
<?php
$x = 'filename';
?>
You can now use it in your function:
<?php
get_template_part($x);
?>
So what Felix is telling you to do is to put the logic that you currently have into a function. In this example:
<?php
function foo()
{
return 'filename';
}
get_template_part(foo());
?>
Now whatever value foo() returns will be sent to your get_template_part().
Taking your code:
$category = get_the_category();
$parent = get_cat_name($category[0]->category_parent);
if (!empty($parent)) {
$name = $parent;
} else {
$name = $category[0]->cat_name;
}
get_template_part($name);
You could take Felix's answer and put it into a file called category_parent.php, and then use it like:
require_once 'category_parent.php'
get_template_part(getName());
Honestly I am not so familiar with Wordpress, but it seems to me, you could do:
function getName() {
$category = get_the_category();
$parent = get_cat_name($category[0]->category_parent);
if (!empty($parent)) {
return '' . $parent;
} else {
return '' . $category[0]->cat_name;
}
}
get_template_part(getName());
konforce is correct about the syntax and, like konforce, I have no idea what you are trying to do. You do not need to use { } because your are not trying to dynamically name a variable and you certainly don't need to escape to php using <?php ?>, as (1) you are already in php and (2) it will stop interpreting PHP and assume html the second it hits the first '?>'.
There is no special syntax for nesting functions. Simply:
get_template_part(get_template_part('category_parent'));
is the syntax, but I have no idea what the function is or does, so I have no idea if that will work.
To debug, why don't you try this:
$parent = get_template_part('category_parent');
echo 'parent: ' . $parent . '<br />';
$result = get_template_part($parent);
echo 'result: ' . $result . '<br />';
When using variables in php strings, you will need to use double quotes ("). I assume option 2 should work then.

Categories