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!
Related
I have a WordPress-theme that has to be used on multiple sites. So I wrote this function, to determine which site the theme is on:
/*
* Check which site
*/
function determine_site() {
$the_site = '';
$URL = $_SERVER['HTTP_HOST'];
switch( $URL ){
case 'domain1.com':
case 'develop1.ment.com':
$the_site = 'domain1_com';
break;
case 'domain2.com':
case 'develop2.ment.com':
$the_site = 'domain2_com';
break;
default;
$the_site = 'domain_undetermined';
break;
}
return $the_site;
}
And this function is then called from another function, which adds it to the body-class on the site, as such:
/*
* Add body class
*/
function add_custom_body_class( $classes ) {
$which_language = determine_site();
$classes[] = $which_language;
return $classes;
}
add_filter( 'body_class', 'add_custom_body_class' );
But it reaches the default-case and sets domain_undetermined as the body-class (which it should match on one of the first cases). If I print out the $URL-var in the top of the determine_site-function, as such:
function determine_site() {
$the_site = '';
$URL = $_SERVER['HTTP_HOST'];
echo '<pre>;
print_r($URL);
echo '</pre>;
...
...
...
Then it outputs this (!?):
develop1.ment.comclass="home page-template-default page page-id-11 logged-in admin-bar no-customize-support wp-custom-logo domain_undetermined">
Why does it print the end of the body-classes, as well?
Another thing that might help figure out where the hatchet is burried... If I run sanitize_title (a WordPress-function) on $URL, as such:
function determine_site() {
$the_site = '';
$URL = $_SERVER['HTTP_HOST'];
$URL = sanitize_title( $URL );
echo '<pre>';
print_r($URL);
echo '</pre>';
...
...
...
... Then it returns this (even though I am on the develop1.ment.com-domain:
www-domain1-comclass="home page-template-default page page-id-11 logged-in admin-bar no-customize-support wp-custom-logo domain_undetermined">
The development-server does some proxy-stuff, which explains this last bit, - but it doesn't explain all of these mysteries.
Would something like this work in place of your own "add body class" function?
/**
* Add domain to body class for each site.
*/
function my_multisite_body_classes( $classes ) {
$current_blog = get_blog_details( get_current_blog_id() );
$classes[] = $current_blog->domain;
return $classes;
}
add_filter('body_class', 'my_multisite_body_classes');
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;}
I have my homepage http://www.faberunashop.com set up as a directory. When you click on the post image, it takes you over to the artists site. Here is the code that I used to make this happen by adding it to the functions.php:
function print_post_title() {
global $post;
$thePostID = $post->ID;
$post_id = get_post($thePostID);
$title = $post_id->post_title;
$perm = get_permalink($post_id);
$post_keys = array(); $post_val = array();
$post_keys = get_post_custom_keys($thePostID);
if (!empty($post_keys)) {
foreach ($post_keys as $pkey) {
if ($pkey=='url1' || $pkey=='title_url' || $pkey=='url_title') {
$post_val = get_post_custom_values($pkey);
}
}
if (empty($post_val)) {
$link = $perm;
} else {
$link = $post_val[0];
}
} else {
$link = $perm;
}
echo '<h2>'.$title.'</h2>';
}
Now I want to do the same to my search and archive page. What do I adjust to make them behave the same?
I suppose that you use WordPress.
In that case you can change the layout and the behavior of your search results by creating a file with name search.php into your theme for your search results, and another file for archives that called archives.php.
For more information about Template Hierarchy for WordPress you can find here http://codex.wordpress.org/Template_Hierarchy
I'm trying to get parameters from the menu table in Joomla. What I have below is working in the sense that it is returning the parameters.
$menu = &JSite::getMenu();
$item = $menu->getItem($menuId)->params;
print $items;
However, It's returning them in plain text, as if I had just queried the column and returned the params contents.
Can someone tell me how to return this as an Object or Array so that I can use something like:
$myParam = $item->getParams('theParamIwant');
I think JParameter is obsolete in Joomla! 3.x, so the answer now is something like:
$app = JFactory::getApplication();
$menuitem = $app->getMenu()->getActive(); // get the active item
$menuitem = $app->getMenu()->getItem($theid); // or get item by ID
$params = $menuitem->params; // get the params
print_r($params); // print all params as overview
You can get the menu_image variable by doing:
echo $params->get('menu_image');
Or first check if it's filled in and, if it is, echo it:
// using get() with a second parameter makes it fall back to this if nothing is found
$menu_image = $params->get('menu_image', false);
if ($menu_image && strlen($menu_image)) {
echo "<img src='$menu_image'/>";
}
Or, using a tertiary operator:
$menuimg = $params->get('menu_image')
echo strlen($menuimg) ? "<img src='$menuimg'/>" : '';
You need to use the JParameter class to read the params. Try something like this:
$item = $menu->getItem($menuId);
$params = new JParameter($item->params);
$myParam = $params->get('theParamIwant');
It doesn't work
Try to use this:
$params = $menus->getParams($menuId);
$myParam = $params->get('theParamIwant');
$app = JFactory::getApplication();
$params = $app->getParams();
$yourParameter = $params->get('YOURPARAMETERNAME');
($currentMenuId = JSite::getMenu()->getActive()->id ; // `enter code here`
$document =& JFactory::getDocument(); // `enter code here`
$app = JFactory::getApplication(); // `enter code here`
$menuitem = $app->getMenu()->getItem($currentMenuId); // or get item by ID `enter code here`
$params = $menuitem->params; // get the params `enter code here`
$params->get('menu-meta_keywords');
if($document->description == '') // 116 is the ID number of the menu pointing to the component `enter code here`
{
$this->setMetaData( 'description', $params->get('menu-meta_description') );
$this->setMetaData( 'keywords', $params->get('menu-meta_keywords') );
}
else
{
// do nothing
})
Working in 3.5.1
$app = JFactory::getApplication();
$currentMenuId = JSite::getMenu()->getActive()->id;
$menuitem = $app->getMenu()->getItem($currentMenuId);
$params = $menuitem->params;
echo $params['menu_image'];
Shows menu item image
JParameter is deprecated in Joomla 2.5, so to get Kevin's code to work add
jimport( 'joomla.html.parameter' ) before i.e
jimport( 'joomla.html.parameter' );
$item = $menu->getItem($menuId);
$params = new JParameter($item->params);
$myParam = $params->get('theParamIwant');
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.