Loading different style sheets per OS - css

Sorry if this question seems redundant but in looking around, I am finding that there are a lot of questions around conditional CSS per browsers, as opposed to, OS.
Is there any way to simply load a different style sheet per OS? (I'm trying to circumvent pixel-walking backgrounds on Mac.) I would preferably need an option that integrates well into a Wordpress child-theme.
Thank you!

the best way is to break it down by user agent and then serve up a different stylesheet. If your using wordperss this will be PHP. #
$_SERVER['HTTP_USER_AGENT']
http://php.about.com/od/learnphp/p/http_user_agent.htm

I had this same question a few years ago. I had to search a while to find the article again, so here's the code from the article:
function get_broswer_stylesheet ($test_by = 'browser')
{
$broswer = array(
'MSIE', // parent
'OPERA',
'MOZILLA',
'NETSCAPE',
'FIREFOX',
'SAFARI',
'CHROME'
);
$os = array(
'MAC',
'WINDOWS',
'LINUX'
);
$info[browser] = 'OTHER';
$info[os] = 'OTHER';
$user_agent = $_SERVER['HTTP_USER_AGENT'];
foreach ($broswer as $parent)
{
$s = strpos(strtoupper($user_agent), $parent);
$f = $s + strlen($parent);
$version = substr($user_agent, $f, 5);
$version = preg_replace('/[^0-9,.]/', '', $version);
if (strpos(strtoupper($user_agent), $parent))
{
$info[browser] = $parent;
$info[version] = $version;
}
}
foreach ($os as $parent)
{
if (strpos(strtoupper($user_agent), $parent))
{
$info[os] = $parent;
}
}
if ($test_by == 'browser' || $test_by == 'os')
{
$string = '<link rel="stylesheet" type="text/css" href="' . get_bloginfo('template_directory') . '/css/';
if ($test_by == 'browser')
{
if ($info[browser] == 'MSIE') {
switch ($info[version])
{
case 9 : $string .= 'ie9.css'; break;
case 8 : $string .= 'ie8.css'; break;
case 7 : $string .= 'ie7.css'; break;
default: $string .= 'ie6.css'; break;
}
} elseif ( $info[browser] == 'FIREFOX') {
$string .= 'firefox.css';
} elseif ($info[browser] == 'SAFARI') {
$string .= 'safari.css';
} elseif ($info[browser] == 'CHROME') {
$string .= 'chrome.css';
} else {
$string .= 'style.css';
}
} elseif ($test_by == 'os') {
if ($info[os] == 'MAC') {
$string .= 'mac.css';
} elseif ($info[os] == 'WINDOWS') {
$string .= 'windows.css';
} elseif ($info[os] == 'LINUX') {
$string .= 'linux.css';
} else {
$string .= 'style.css';
}
}
$string .= '">';
return $string;
}
}
I hope that helps. You can set the $test_by parameter to either browser or os and it'll try to deliver the right stylesheet.

Related

Function to check status of gravityforms wordpress

I am trying to make a function to check if the gform has some entries, has all entries or is empty and return $status according to status.
I have looped through the entries and checked if they are infact shown as an empty string if empty but I only ever get partial or empty.
function set_form_status($form_id) {
$entries = GFAPI::get_entries( $form_id, entry_search_criteria());
$status = '';
if (count($entries) > 0) {
foreach($entries as $entry) {
$keys = array_keys($entry);
foreach($keys as $key) {
if ($entry[$key] === '') {
$status = 'partial';
}
if ($entry[$key] !== '') {
$status = 'filled';
}
}
}
} else {
$status = 'empty';
}
return $status;
}
I'd suggest running it like below and seeing what gets returned. I did remove the entry_search_criteria function but other than that I'm just echoing the key/value.
What I found was even if I'm not using purchasing in a form, there are fields created for it and they are empty. They don't show on the back end entry view even if I select show empty fields. You may have a similar scenario.
function set_form_status($form_id) {
$entries = GFAPI::get_entries( $form_id);
$status = '';
if (count($entries) > 0) {
foreach($entries as $entry) {
$keys = array_keys($entry);
foreach($keys as $key) {
echo $key . ' - ' . $entry[$key] . '<br>';
if ($entry[$key] === '') {
$status = 'partial';
}
if ($entry[$key] !== '') {
$status = 'filled';
}
}
}
} else {
$status = 'empty';
}
return $status;
}
Did some refactoring and debugging together with a co-worker, there was HTML fields on all of the forms and all of them returned an empty string. This is the working version.
function set_form_status($form) {
define('FORM_EMPTY', 0);
define('FORM_PARTIAL', 1);
define('FORM_FILLED', 2);
//checks if the form is my special kind of form
if (is_eligible_form($form)) {
$earlier_entry = get_last_entry($form['id']);
if ($earlier_entry === false) {
return STATUS_EMPTY;
} else {
foreach($form['fields'] as $key => $field) {
if ($earlier_entry[$field->id] === '' && $field->type !== 'html') {
return FORM_PARTIAL;
}
}
}
}
return FORM_FILLED;
}

Problem removing sub category from permalink URL of blog post in Wordpress

I'm using this solution to remove sub-categories from the url on my blog posts:
Remove sub category slug from permalink URL of blog post and custom post type in WordPress
add_filter('post_link','custom_post_type_link',10,3);
function custom_post_type_link($permalink, $post, $leavename) {
if (!gettype($post) == 'post') {
return $permalink;
}
switch ($post->post_type) {
case 'post':
//$permalink = get_home_url() . '/' . $post->post_name . '/';
$cats = get_the_category($post->ID);
$subcats = array();
foreach( $cats as $cat ) {
$cat = get_category($cat->term_id);
if($cat->parent) { $subcats[] = sanitize_title($cat->name); }
}
if($subcats) {
foreach($subcats as $subcat) {
$subcat = $subcat.'/';
$permalink = str_replace($subcat, "", $permalink);
}
}
break;
}
return $permalink;}
It's working fine but there is still a little problem with the code.
If I have an URL like this:
www.myblog.com/parentcategory/nameofchildcategory/slugpost
I will get this:
www.myblog.com/parentcategory/slugpost
Which is exactly what I want.
But if I have an URL like this:
www.myblog.com/parentcategory/nameofchildcategory/slugpost-with-nameofchildcategory
I will get this:
www.myblog.com/parentcategory/slugpost-with- (mssing the end of the slug)
...and a 404 page for every link to this article.
So the problem is that when the child category text appears in the slug's post, the code will also remove this part of the URL.
Anyone have an idea on how to solve this?
Thanks in advance!
I have found this solution, adding two functions. I'm not sure the code is optimal but it works perfectly.
add_filter('post_link','custom_post_type_link',10,3);
//function to see if URL ends with...
function endsWith($string, $endString) {
$len = strlen($endString);
if ($len == 0) {
return true;
}
return (substr($string, -$len) === $endString);
}
//function to replace only first match
function str_replace_first($from, $to, $content)
{
$from = '/'.preg_quote($from, '/').'/';
return preg_replace($from, $to, $content, 1);
}
function custom_post_type_link($permalink, $post, $leavename) {
if (!gettype($post) == 'post') {
return $permalink;
}
switch ($post->post_type) {
case 'post':
//$permalink = get_home_url() . '/' . $post->post_name . '/';
$cats = get_the_category($post->ID);
$subcats = array();
foreach( $cats as $cat ) {
$cat = get_category($cat->term_id);
if($cat->parent) { $subcats[] = sanitize_title($cat->name); }
}
if($subcats) {
foreach($subcats as $subcat) {
$subcat = $subcat.'/';
//If URL ends with category name
if(endsWith($permalink,$subcat)){
//And if the category name appears more than once
if(substr_count($permalink,$subcat)>1){
// Remove only first match
$permalink = str_replace_first($subcat, "", $permalink);
}else{
//do nothing
}
}
// If URL does NOT end with category name
else{
$permalink = str_replace($subcat, "", $permalink);
}
}
}
break;
}
return $permalink;}
Try delimiting both ends of the slug, like:
foreach ($subcats as $subcat) {
$permalink = str_replace('/'.$subcat.'/', '/', $permalink);
}

how to remove custom post type from wordpress url?

I have a wordpress website which is using the custom template with custom post types like landing and services.
Each post type have a specific slug in the url like this => (http://example.com/landing/landing-page-name)
I want to change this url (http://example.com/landing/landing-page-name) to this url (http://example.com/landing-page-name).
In fact I need to remove the [landing] phrase from the url. The important thing is that the [landing] is a custom post type in my posts table.
I have tested following solutions:
==> I have changed slug to '/' in rewrite property in register_post_type() --> It breaks the all of landings, posts and pages url (404)
==> I added 'with_front' => false to the rewrite property --> nothing changed
==> I tried to do this with RewriteRule in htaccess --> it did not work or give too many redirects error
I could not get a proper result.
Did anyone solve this problem before?
First, you need to filter the permalink for your custom post type so that all published posts don't have the slug in their URLs:
function stackoverflow_remove_cpt_slug( $post_link, $post ) {
if ( 'landing' === $post->post_type && 'publish' === $post->post_status ) {
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
}
return $post_link;
}
add_filter( 'post_type_link', 'stackoverflow_remove_cpt_slug', 10, 2 );
At this point, trying to view the link would result in a 404 (Page Not Found) error. That's because WordPress only knows that Posts and Pages can have URLs like domain.com/post-name/ or domain.com/page-name/. We need to teach it that our custom post type's posts can also have URLs like domain.com/cpt-post-name/.
function stackoverflow_add_cpt_post_names_to_main_query( $query ) {
// Return if this is not the main query.
if ( ! $query->is_main_query() ) {
return;
}
// Return if this query doesn't match our very specific rewrite rule.
if ( ! isset( $query->query['page'] ) || 2 !== count( $query->query ) ) {
return;
}
// Return if we're not querying based on the post name.
if ( empty( $query->query['name'] ) ) {
return;
}
// Add CPT to the list of post types WP will include when it queries based on the post name.
$query->set( 'post_type', array( 'post', 'page', 'landing' ) );
}
add_action( 'pre_get_posts', 'stackoverflow_add_cpt_post_names_to_main_query' );
try this code , 100% working single custom post type and multiple post type.
add this class in functions.php file in our theme , or create separate file and import into functions.php
class remove_cpt_base {
var $plugin_admin_page;
static $instance = null;
static public function init() {
if (self::$instance == null) {
self::$instance = new self();
}
return self::$instance;
}
function __construct() {
add_action('plugins_loaded', array($this, 'plugins_loaded'));
$this->rcptb_selected = get_option('rcptb_selected', array());
$this->rcptb_selected_keys = array_keys($this->rcptb_selected);
add_action('admin_menu', array($this, 'plugin_menu_link'));
add_filter('post_type_link', array($this, 'remove_slug'), 10, 3);
add_action('template_redirect', array($this, 'auto_redirect_old'), 1);
add_action('pre_get_posts', array($this, 'handle_cpts'), 1);
}
function plugins_loaded() {
load_plugin_textdomain('remove_cpt_base', FALSE, basename(dirname(__FILE__)) . '/languages/');
}
function filter_plugin_actions($links, $file) {
$settings_link = '' . __('Settings') . '';
array_unshift($links, $settings_link);
return $links;
}
function plugin_menu_link() {
$this->plugin_admin_page = add_submenu_page(
'options-general.php',
__('Remove CPT base', 'remove_cpt_base'),
__('Remove CPT base', 'remove_cpt_base'),
'manage_options',
basename(__FILE__),
array($this, 'admin_options_page')
);
add_filter('plugin_action_links_' . plugin_basename(__FILE__), array($this, 'filter_plugin_actions'), 10, 2);
}
function admin_options_page() {
if (get_current_screen()->id != $this->plugin_admin_page) {
return;
}
global $wp_post_types;?>
<div class="wrap">
<h2><?php _e('Remove base slug from url for these custom post types:', 'remove_cpt_base')?></h2><?php
if (isset($_POST['rcptb_selected_sent'])) {
if (!isset($_POST['rcptb_alternation']) || !is_array($_POST['rcptb_alternation'])) {
$alternation = array();
} else {
$alternation = $_POST['rcptb_alternation'];
}
if (!isset($_POST['rcptb_selected']) || !is_array($_POST['rcptb_selected'])) {
$this->rcptb_selected = array();
} else {
$this->rcptb_selected = $_POST['rcptb_selected'];
}
foreach ($this->rcptb_selected as $post_type => $active) {
$this->rcptb_selected[$post_type] = isset($alternation[$post_type]) ? 1 : 0;
}
$this->rcptb_selected_keys = array_keys($this->rcptb_selected);
update_option('rcptb_selected', $this->rcptb_selected, 'no');
echo '<div class="below-h2 updated"><p>' . __('Settings saved.') . '</p></div>';
flush_rewrite_rules();
}?>
<br>
<form method="POST" action="">
<input type="hidden" name="rcptb_selected_sent" value="1">
<table class="widefat" style="width:auto">
<tbody><?php
foreach ($wp_post_types as $type => $custom_post) {
if ($custom_post->_builtin == false) {?>
<tr>
<td>
<label>
<input type="checkbox" name="rcptb_selected[<?php echo $custom_post->name ?>]" value="1" <?php echo isset($this->rcptb_selected[$custom_post->name]) ? 'checked' : '' ?>>
<?php echo $custom_post->label ?> (<?php echo $custom_post->name ?>)
</label>
</td>
<td>
<label>
<input type="checkbox" name="rcptb_alternation[<?php echo $custom_post->name ?>]" value="1" <?php echo isset($this->rcptb_selected[$custom_post->name]) && $this->rcptb_selected[$custom_post->name] == 1 ? 'checked' : '' ?>>
<?php _e('alternation', 'remove_cpt_base')?>
</label>
</td>
</tr><?php
}
}?>
</tbody>
</table>
<p><?php _e('* if your custom post type children return error 404, then try alternation mode', 'remove_cpt_base')?></p>
<hr>
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e('Save')?>">
</p>
</form>
</div><?php
}
function remove_slug($permalink, $post, $leavename) {
global $wp_post_types;
foreach ($wp_post_types as $type => $custom_post) {
if ($custom_post->_builtin == false && $type == $post->post_type && isset($this->rcptb_selected[$custom_post->name])) {
$custom_post->rewrite['slug'] = trim($custom_post->rewrite['slug'], '/');
$permalink = str_replace('/' . $custom_post->rewrite['slug'] . '/', '/', $permalink);
}
}
return $permalink;
}
function get_current_url() {
$REQUEST_URI = strtok($_SERVER['REQUEST_URI'], '?');
$real_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
$real_url .= $_SERVER['SERVER_NAME'] . $REQUEST_URI;
return $real_url;
}
function handle_cpts($query) {
// make sure it's main query on frontend
if (!is_admin() && $query->is_main_query() && !$query->get('queried_object_id')) {
// conditions investigated after many tests
if ($query->is_404() || $query->get('pagename') || $query->get('attachment') || $query->get('name') || $query->get('category_name')) {
// test both site_url and home_url
$web_roots = array();
$web_roots[] = site_url();
if (site_url() != home_url()) {
$web_roots[] = home_url();
}
// polylang fix
if (function_exists('pll_home_url')) {
if (site_url() != pll_home_url()) {
$web_roots[] = pll_home_url();
}
}
foreach ($web_roots as $web_root) {
// get clean current URL path
$path = $this->get_current_url();
$path = str_replace($web_root, '', $path);
// fix missing slash
if (substr($path, 0, 1) != '/') {
$path = '/' . $path;
}
// test for posts
$post_data = get_page_by_path($path, OBJECT, 'post');
if (!($post_data instanceof WP_Post)) {
// test for pages
$post_data = get_page_by_path($path);
if (!is_object($post_data)) {
// test for selected CPTs
$post_data = get_page_by_path($path, OBJECT, $this->rcptb_selected_keys);
if (is_object($post_data)) {
// maybe name with ancestors is needed
$post_name = $post_data->post_name;
if ($this->rcptb_selected[$post_data->post_type] == 1) {
$ancestors = get_post_ancestors($post_data->ID);
foreach ($ancestors as $ancestor) {
$post_name = get_post_field('post_name', $ancestor) . '/' . $post_name;
}
}
// get CPT slug
$query_var = get_post_type_object($post_data->post_type)->query_var;
// alter query
$query->is_404 = 0;
$query->tax_query = NULL;
$query->is_attachment = 0;
$query->is_category = 0;
$query->is_archive = 0;
$query->is_tax = 0;
$query->is_page = 0;
$query->is_single = 1;
$query->is_singular = 1;
$query->set('error', NULL);
unset($query->query['error']);
$query->set('page', '');
$query->query['page'] = '';
$query->set('pagename', NULL);
unset($query->query['pagename']);
$query->set('attachment', NULL);
unset($query->query['attachment']);
$query->set('category_name', NULL);
unset($query->query['category_name']);
$query->set('post_type', $post_data->post_type);
$query->query['post_type'] = $post_data->post_type;
$query->set('name', $post_name);
$query->query['name'] = $post_name;
$query->set($query_var, $post_name);
$query->query[$query_var] = $post_name;
break;
} else {
// deeper matching
global $wp_rewrite;
// test all selected CPTs
foreach ($this->rcptb_selected_keys as $post_type) {
// get CPT slug and its length
$query_var = get_post_type_object($post_type)->query_var;
// test all rewrite rules
foreach ($wp_rewrite->rules as $pattern => $rewrite) {
// test only rules for this CPT
if (strpos($pattern, $query_var) !== false) {
if (strpos($pattern, '(' . $query_var . ')') === false) {
preg_match_all('#' . $pattern . '#', '/' . $query_var . $path, $matches, PREG_SET_ORDER);
} else {
preg_match_all('#' . $pattern . '#', $query_var . $path, $matches, PREG_SET_ORDER);
}
if (count($matches) !== 0 && isset($matches[0])) {
// build URL query array
$rewrite = str_replace('index.php?', '', $rewrite);
parse_str($rewrite, $url_query);
foreach ($url_query as $key => $value) {
$value = (int) str_replace(array('$matches[', ']'), '', $value);
if (isset($matches[0][$value])) {
$value = $matches[0][$value];
$url_query[$key] = $value;
}
}
// test new path for selected CPTs
if (isset($url_query[$query_var])) {
$post_data = get_page_by_path('/' . $url_query[$query_var], OBJECT, $this->rcptb_selected_keys);
if (is_object($post_data)) {
// alter query
$query->is_404 = 0;
$query->tax_query = NULL;
$query->is_attachment = 0;
$query->is_category = 0;
$query->is_archive = 0;
$query->is_tax = 0;
$query->is_page = 0;
$query->is_single = 1;
$query->is_singular = 1;
$query->set('error', NULL);
unset($query->query['error']);
$query->set('page', '');
$query->query['page'] = '';
$query->set('pagename', NULL);
unset($query->query['pagename']);
$query->set('attachment', NULL);
unset($query->query['attachment']);
$query->set('category_name', NULL);
unset($query->query['category_name']);
$query->set('post_type', $post_data->post_type);
$query->query['post_type'] = $post_data->post_type;
$query->set('name', $url_query[$query_var]);
$query->query['name'] = $url_query[$query_var];
// solve custom rewrites, pagination, etc.
foreach ($url_query as $key => $value) {
if ($key != 'post_type' && substr($value, 0, 8) != '$matches') {
$query->set($key, $value);
$query->query[$key] = $value;
}
}
break 3;
}
}
}
}
}
}
}
}
}
}
}
}
}
function auto_redirect_old() {
global $post;
if (!is_preview() && is_single() && is_object($post) && isset($this->rcptb_selected[$post->post_type])) {
$new_url = get_permalink();
$real_url = $this->get_current_url();
if (substr_count($new_url, '/') != substr_count($real_url, '/') && strstr($real_url, $new_url) == false) {
remove_filter('post_type_link', array($this, 'remove_slug'), 10);
$old_url = get_permalink();
add_filter('post_type_link', array($this, 'remove_slug'), 10, 3);
$fixed_url = str_replace($old_url, $new_url, $real_url);
wp_redirect($fixed_url, 301);
}
}
}
}
function rcptb_remove_plugin_options() {
delete_option('rcptb_selected');
}
add_action('init', array('remove_cpt_base', 'init'), 99);
register_activation_hook(__FILE__, 'flush_rewrite_rules');
register_deactivation_hook(__FILE__, 'flush_rewrite_rules');
register_uninstall_hook(__FILE__, 'rcptb_remove_plugin_options');
To the rewrite you just have to change your current slug from ‘cpt-slug’ to ‘/’ and the with-front: ‘false’. And done, you just resave permalinks and the url shouldn’t display the cpt slug anymore.
Having same issue and came across this answer and none of the above mentioned solution works so tried different plugins and the best which worked, removed base slug and solved 404 error try Remove CPT base

Redirect to login page if user is not logged in wordpress?

http://localhost/finsafe/calculator/sip.html
If i type the above url I want it to redirect to my login page
Following is my code
if(!is_user_logged_in() && curPageURL() = 'http://localhost/finsafe/calculator/sip.html') {
wp_redirect( 'http://localhost/finsafe/wp-login.php?redirect_to=http%3A%2F%2Flocal%3A8095%2Ffinsafe%2Fcontact%2F/', 302 );
exit;
}
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
But it doesnt work can anyone help
It's because your page is a .html file and you're trying to run PHP code on it. You'll need to save your .html file out as a .php file instead and then try again. Then wrap your PHP code in php tags like so...
<?php
if(!is_user_logged_in() && curPageURL() = 'http://localhost/finsafe/calculator/sip.html') {
wp_redirect( 'http://localhost/finsafe/wp-login.php?redirect_to=http%3A%2F%2F183.82.33.232%3A8095%2Ffinsafe%2Fcontact%2F/', 302 );
exit;
}
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>
Try This:
add_action( 'template_redirect', 'redirect_to_specific_page' );
function redirect_to_specific_page() {
if ( is_page('slug') && ! is_user_logged_in() ) {
wp_redirect( 'http://www.example.dev/your-page/', 301 );
exit;
}
}
You can simply use the Force login plugin https://wordpress.org/plugins/wp-force-login/
You can simply check like this also :
if ( is_user_logged_in() ) {
echo "user logged in";
} else {
header('Location: ' . wp_login_url());
}

how to display the taxonomy terms in hierarchies order?

I have a vocabulary which displays the terms in the hierarchies order like the following.
parent1
child1
child2
parent2
child1
parent3
parent4
child1
child2
child3
This displays in taxonomy manager.
I want to create a page on which I call a function and pass the vid and displays the taxonomy terms of that vocabulary in hierarchies order just like in taxonomy manager.
I used the following code but it displays only the taxonomy terms not in a tree order.
$vid = 26;
$tree = taxonomy_get_tree($vid);
foreach($tree as $term) {
$output = l($term->name, taxonomy_term_path($term));
if ($term->children) {
$output .= theme('illogica_category_tree', $term->children);
}
}
print $output;
Any idea about this?
I use this:
$tree = extranet_get_nested_tree((int)$vid, null, $tid);
With this:
function extranet_get_nested_tree($terms = array(), $max_depth = NULL, $parent = 0, $parents_index = array(), $depth = 0) {
if (is_int($terms)) {
$terms = taxonomy_get_tree($terms);
}
foreach($terms as $term) {
foreach($term->parents as $term_parent) {
if ($term_parent == $parent) {
$return[$term->tid] = $term;
}
else {
$parents_index[$term_parent][$term->tid] = $term;
}
}
}
foreach($return as &$term) {
if (isset($parents_index[$term->tid]) && (is_null($max_depth) || $depth < $max_depth)) {
$term->children = extranet_get_nested_tree($parents_index[$term->tid], $max_depth, $term->tid, $parents_index, $depth + 1);
}
}
return $return;
}
And to print it out:
function extranet_output_nested_tree($tree) {
if (count($tree)) {
$output = '<ul class="nested-taxonomy-tree">';
foreach ($tree as $term) {
$output .= '<li class="taxonomy-term">';
$output .= t($term->name); //, taxonomy_term_path($term));
if ($term->children) {
$output .= extranet_output_nested_tree( $term->children);
}
$output .= '</li>';
}
$output .= '</ul>';
}
return $output;
}
Enjoy!
taxonomy_get_tree() should return the terms in the correct order, but the array is flat rather than nested. See taxonomy_get_tree() for more information and some sample functions to get a nested array.
Here is the solution `
foreach($terms as $term) {
foreach($term->parents as $term_parent) {
if ($term_parent == $parent) {
$return[$term->tid] = $term;
}
else {
$parents_index[$term_parent][$term->tid] = $term;
}
}
}
foreach($return as &$term) {
if (isset($parents_index[$term->tid]) && (is_null($max_depth) || $depth < $max_depth)) {
$term->children = taxonomy_get_nested_tree($parents_index[$term->tid], $max_depth, $term->tid, $parents_index, $depth + 1);
}
}
return $return;
}
function output_taxonomy_nested_tree($tree) {
if (count($tree)) {
$output = '<ul class="nav navbar-nav">';
foreach ($tree as $term) {
$output .= '<li class="taxonomy-term">' . l($term->name, "taxonomy/term/". $term->tid);
if ($term->children) {
$output .= output_taxonomy_nested_tree($term->children);
}
$output .= '</li>';
}
$output .= '</ul>';
}
return $output;
}
$tree= taxonomy_get_nested_tree(2,10);
$output=output_taxonomy_nested_tree($tree);
echo $output;`
If you want to print it in the specific region you needed just assign the output to a variable in preprocessor function and print the variable in the page tpl file.
$output=output_taxonomy_nested_tree($tree);
echo $output;`
to
$variables['output'] .=output_taxonomy_nested_tree($tree);
place the line
<?php print $output;?>
in your page tpl file

Resources