How can I check if a category exists, and if exists, return the ID; if not, create the category?
Use Wordpress is_category(), get_cat_ID() and wp_create_category() method.
<?php
$CategoryName = "books";
if(is_category($CategoryName))
$categoryID = get_cat_ID($CategoryName);
else
$categoryID = wp_create_category($CategoryName);
?>
See wp_create_category().
include( "../../wordpress/wp-config.php" );
include( "../../wordpress/wp-admin/includes/taxonomy.php" );
$cat_id = wp_create_category( "TESTINGLOL" );
echo "created = {$cat_id}\n";
echo "returned = " . get_cat_ID( "TESTINGLOL" );
Output should go like:
created = 37450 returned = 37450
Note that this isn't very efficient, but, does the job.
create_category_if_not_exist($category_name, $echo = true) {
$id = wp_insert_term( $category_name, 'category');
if ( $echo ) return $id;
return $id;
}
Nice all in one function for doing the trick. $category_name would need to be the category slug though.
wp_insert_term() takes care of checking if the category already exists in the database. It will return the $id of the category if it exists and will return the $id of the newly created category if it doesn't pre-exist.
Related
Currently, I have two categories to separate my WordPress blog posts.
site.com/category/slow/
site.com/category/fast/
As you can see, my site's category base is 'category'.
My permalink settings on the Dashboard under Settings->Permalinks is set to "site.com/%postname%/".
This means that all my blog posts will appear like this: "site.com/post-title/" regardless of which category I assign the post to.
The thing is, I want to remove the category base from the URL so that they become:
site.com/slow/
site.com/fast/
And at the same time, without altering the permalink setting so that my blog posts' URL continue to look like "site.com/post-title/". How can I achieve these?
Here's the solution after I modified a bit the code I found:
// Remove category base
function no_category_base_permastruct() {
global $wp_rewrite;
$wp_rewrite -> extra_permastructs['category']['struct'] = '%category%';
}
add_action('init', 'no_category_base_permastruct');
// Add our custom category rewrite rules
function no_category_base_rewrite_rules($category_rewrite) {
//var_dump($category_rewrite); // For Debugging
$category_rewrite = array();
$categories = get_categories(array('hide_empty' => false));
foreach ($categories as $category) {
$category_nicename = $category -> slug;
if ($category -> parent == $category -> cat_ID)// recursive recursion
$category -> parent = 0;
elseif ($category -> parent != 0)
$category_nicename = get_category_parents($category -> parent, false, '/', true) . $category_nicename;
$category_rewrite['(' . $category_nicename . ')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
$category_rewrite['(' . $category_nicename . ')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
$category_rewrite['(' . $category_nicename . ')/?$'] = 'index.php?category_name=$matches[1]';
}
// Redirect support from Old Category Base
global $wp_rewrite;
$old_category_base = get_option('category_base') ? get_option('category_base') : 'category';
$old_category_base = trim($old_category_base, '/');
$category_rewrite[$old_category_base . '/(.*)$'] = 'index.php?category_redirect=$matches[1]';
//var_dump($category_rewrite); // For Debugging
return $category_rewrite;
}
add_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
// Add 'category_redirect' query variable
function no_category_base_query_vars($public_query_vars) {
$public_query_vars[] = 'category_redirect';
return $public_query_vars;
}
add_filter('query_vars', 'no_category_base_query_vars');
// Redirect if 'category_redirect' is set
function no_category_base_request($query_vars) {
//print_r($query_vars); // For Debugging
if (isset($query_vars['category_redirect'])) {
$catlink = trailingslashit(get_option('home')) . user_trailingslashit($query_vars['category_redirect'], 'category');
status_header(301);
header("Location: $catlink");
exit();
}
return $query_vars;
}
add_filter('request', 'no_category_base_request');
Rewrite your ,htaccess File
RewriteRule ^/([a-zA-Z0-9-/]+)$ category/file_name.php?value=$1
My project is with Webservices add categories and when I refresh the file of categories it creates the same categories I had before.
foreach ($XMLRSString->Families->Family as $family)
{
$categories = $family->Code;
$exists = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('select id_category from ps_category where id_category = "'.$categories['id_category'].'"');
$category = new Category((int)$categories);
$category->id= (int)$categories;
$category->id_category_default=(int)$family->Code;
$category->force_id = true;
$category->is_root_category = false;
$category->name = array((int)Configuration::get('PS_LANG_DEFAULT') => $family->Designation);
$category->link_rewrite = array((int)Configuration::get('PS_LANG_DEFAULT') => $family->Code);
$category->id_parent = Configuration::get('PS_HOME_CATEGORY');
if($exists){
$category->add();
echo "created ".$family->Code."<br>";
}
else{
$category->save();
echo "already exists ".$family->Code."<br>";
}
}
It doesn't appear any error but it doesn't show up on PrestaShop categories
No need to use if ($exists), as $category->save(); will already check if the category exists, if so it will update it, otherwise it will create it.
You can refer to your previous question on this topic:
How to test if a category already exists? PrestaShop
I think your issue comes from the fact your forgot to set the category as active:
$category->active = 1;
Also, you should check the return value of $category->save();.
I hope this helps!
I want to get unique slug for my articles. I am using codeigniter. I was wondering to have some thing like sample-title-1 and sample-title-2 if there are two articles that have the same title like codeignier does with file upload filename(:num) . I could not figure out a way to do it. I am not an expert on codeigniter. I am learning it.
I prepared a function, when passed a string $str it checks if the slug exists, if it does, it adds the ID of that article to the end of that slug and returns it, if not, it returns the slug.
It is working fine and serving the purpose of unique slug. But what I wanted was to have something like sample-title-1 and sample-title-2 . Is there any way to do so?
$data['slug'] = $this->get_slug($data['title']);
public function get_slug ($str)
{
$slug = url_title($str, 'dash', true);
// Do NOT validate if slug already exists
// UNLESS it's the slug for the current page
$id = $this->uri->segment(4);
$this->db->where('slug', $slug);
! $id || $this->db->where('id !=', $id);
$category = $this->category_m->get();
if (count($category)) {
return $slug.$id;
}
return $slug;
}
easy to use and really helpful to create unique slugs have look on CI slug library
read its documentation to implement it.
what i used to do is to make slug db field UNIQUE.
Then easly do all with the CI helpers Url Helper and Text Helper
$last_id_inserted = //get from db the last post's ID;
$post_title = "My slug would be";
$slug = mb_strtolower(url_title(convert_accented_characters($post_title))).'-'.$last_id_inserted;
echo $slug;
//outputting my-slug-would-be-123
//insert the new post with slug
So ID will be unique and slug too.
I think you need something like that:
//Database loaded
//Text helper loaded
function post_uniq_slug($slug, $separator='-', $increment_number_at_end=FALSE) {
//check if the last char is a number
//that could break this script if we don't handle it
$last_char_is_number = is_numeric($slug[strlen($slug)-1]);
//add a point to this slug if needed to prevent number collision..
$slug = $slug. ($last_char_is_number && $increment_number_at_end? '.':'');
//if slug exists already, increment it
$i=0;
$limit = 20; //for security reason
while( get_instance()->db->where('slug', $slug)->count_all_results('posts') != 0) {
//increment the slug
$slug = increment_string($slug, $separator);
if($i > $limit) {
//break;
return FALSE;
}
$i++;
}
//so now we have unique slug
//remove the dot create because number collision
if($last_char_is_number && $increment_number_at_end) $slug = str_replace('.','', $slug);
return $slug;
}
Examples:
post_uniq_slug('sample'); //"sample" exists
//sample-1
post_uniq_slug('sample-2013'); //"sample-2013" exists
//sample-2013-2
post_uniq_slug('sample-2013', '-', TRUE); //increment "sample-2013"
//sample-2014
*NOT TESTED
public function create_slug($name)
{
$table='tradeshow'; //Write table name
$field='slug'; //Write field name
$slug = $name; //Write title for slug
$slug = url_title($name);
$key=NULL;
$value=NULL;
$i = 0;
$params = array ();
$params[$field] = $slug;
if($key)$params["$key !="] = $value;
while ($this->db->from($table)->where($params)->get()->num_rows())
{
if (!preg_match ('/-{1}[0-9]+$/', $slug ))
$slug .= '-' . ++$i;
else
$slug = preg_replace ('/[0-9]+$/', ++$i, $slug );
$params [$field] = $slug;
}
return $alias=$slug;}
With the code blow I retrieve the current parent category and his children. Is it possible to add an active class for the current child?
<?php
$currentCat = Mage::registry('current_category');
if ( $currentCat->getParentId() == Mage::app()->getStore()->getRootCategoryId() )
{
$loadCategory = $currentCat;
}
else
{
$loadCategory = Mage::getModel('catalog/category')->load($currentCat->getParentId());
}
$subCategories = explode(',', $loadCategory->getChildren());
foreach ( $subCategories as $subCategoryId )
{
$cat = Mage::getModel('catalog/category')->load($subCategoryId);
if($cat->getIsActive())
{
echo '<li>'.$cat->getName().'</li>';
}
}
?>
You already have the current category, so you can check it's ID against the IDs of the categories being looped through.
Where you have
echo '<li>'.$cat->getName().'</li>';
Change it to do the check for the ID and then add the "active" class when found
$class = '';
if ($currentCat->getId() == $cat->getId())
{
$class = ' class="active"';
}
echo '<li'.$class.'>'.$cat->getName().'</li>';
To set the category as active we have to set the current category in catalog layer.
$_categoryName=YourCategoryName;
$_category = Mage::getModel('catalog/category')->loadByAttribute('name', $_categoryName);
Mage::getSingleton('catalog/layer')->setCurrentCategory($_category);
This looks better than ugly hack of changing in phtml filter..
I want to get the page ID before starting the loop in WordPress. I am using
$page = get_query_var('page_id');
Apparently, it returns nothing.
I just want to check a page for its ID and add a class to <body> tag based on it.
If you're using pretty permalinks, get_query_var('page_id') won't work.
Instead, get the queried object ID from the global $wp_query:
// Since 3.1 - recommended!
$page_object = get_queried_object();
$page_id = get_queried_object_id();
// "Dirty" pre 3.1
global $wp_query;
$page_object = $wp_query->get_queried_object();
$page_id = $wp_query->get_queried_object_id();
You can also create a generic function to get the ID of the post, whether its outside or inside the loop (handles both the cases):
<?php
/**
* #uses WP_Query
* #uses get_queried_object()
* #see get_the_ID()
* #return int
*/
function get_the_post_id() {
if (in_the_loop()) {
$post_id = get_the_ID();
} else {
global $wp_query;
$post_id = $wp_query->get_queried_object_id();
}
return $post_id;
} ?>
And simply do:
$page_id = get_the_post_id();
Use this global $post instead:
global $post;
echo $post->ID;
If you by any means searched this topic because of the post page (index page alternative when using static front page), then the right answer is this:
if (get_option('show_on_front') == 'page') {
$page_id = get_option('page_for_posts');
echo get_the_title($page_id);
}
(taken from Forrst | Echo WordPress "Posts Page" title - Some code from tammyhart)
If you're on a page and this does not work:
$page_object = get_queried_object();
$page_id = get_queried_object_id();
you can try to build the permalink manually with PHP so you can lookup the post ID:
// get or make permalink
$url = !empty(get_the_permalink()) ? get_the_permalink() : (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$permalink = strtok($url, '?');
// get post_id using url/permalink
$post_id = url_to_postid($url);
// want the post or postmeta? use get_post() or get_post_meta()
$post = get_post($post_id);
$postmeta = get_post_meta($post_id);
It may not catch every possible permalink (especially since I'm stripping out the query string), but you can modify it to fit your use case.
I have done it in the following way and it has worked perfectly for me.
First declared a global variable in the header.php, assigning the ID of the post or page before it changes, since the LOOP assigns it the ID of the last entry shown:
$GLOBALS['pageid] = $wp_query->get_queried_object_id();
And to use anywhere in the template, example in the footer.php:
echo $GLOBALS['pageid];
You can use is_page($page_id) outside the loop to check.
This function get id off a page current.
get_the_ID();
Use below two lines of code to get current page or post ID
global $post;
echo $post->ID;
This is the correct code.
echo $post->ID;
If you are out of the Loop of WordPress you can not use any of the method of wordpress so you must use pure php.
You can use this code. And sure will help you :)
$page_id = #$_GET['page_id'];
if (!is_numeric($page_id)) {
// Then the uri must be in friendly format aka /my_domain/category/onepage/
// Try this
//$path = '/www/public_html/index.php/';
///$path = '/my_domain/category/onepage/';
$path = $_SERVER['REQUEST_URI'];
// Clean the uri
//$path = str_replace('/', '', $page);
$path = str_replace('.php', '', $path);
//$path = str_replace('?s=', '', $path);
$path = $path ? $path : 'default';
$path_len = strlen($path);
$last_char = substr($path, $path_len -1);
//echo $last_char;
$has_slash = strpos($last_char, "/");
//echo $has_slash;
if ($has_slash === 0) :
$path = substr($path, 0, $path_len -1);
elseif ($has_slash === null) :
$path = substr($path, 0, $path_len);
endif;
//echo "path: ".$path; // '/www/public_html/index'
$page = substr(strrchr($path, "/"), 1);
echo "page: ".$page; // 'index'
}
$my_page_id = 31;
$my_page = 'mypage';
//echo "page: ".$page;
//echo "page_id ".$page_id;
if($page_id == $my_page_id || $page == $my_page)
{
// your stuff....
}
Enjoy!