How to get current post_id in function.php file - wordpress

This is my function in function.php file
function getcity(){
global $wpdb;
if($_POST['state'])
{
$id=$_POST['state'];
$district = get_post_meta(get_the_ID() , 'district', true);
var_dump($district);
$result=$wpdb->get_results("SELECT * FROM districts WHERE state_id='$id'");
foreach($result as $row) {
$district_name = $row-
>district_name;
$district_id = $row->district_id;
echo '<option value="'.$district_id.'">'.$district_name.'</option>';
}
}
}
add_action("wp_ajax_nopriv_getcity", "getcity");
add_action("wp_ajax_getcity", "getcity");
I want to get current post id in this function to display selected dropdown value..

Note that $post or get_queried_object_id() do not work until the first query was fired. So these options are available only at the hook template_redirect and later. But functions.php is included much earlier (before the hook after_setup_theme) so this isn't a solution.
A function that should work pretty much anywhere would be:
$url = 'http://' . $_SERVER[ 'HTTP_HOST' ] . $_SERVER[ 'REQUEST_URI' ];
$current_post_id = url_to_postid( $url );
Here is a overview over hook execution order.
As mentioned in the comments url_to_postid may be heavy in some setups, so if your code is executed after template_redirect you better use one of the solutions below as they are most likely much faster than the snippet above:
global $post;
$id = $post->id;
or
$id = get_queried_object_id();

Here is one my function what never fail.
I don't know why WordPress not made something like this before.
/**
* Get current page ID
* #autor Ivijan-Stefan Stipic
* #version 2.0.0
**/
function get_current_page_ID(){
static $current_page_ID;
if(!$current_page_ID) return $current_page_ID;
global $post, $wp_query, $wpdb;
if(!is_null($wp_query) && isset($wp_query->post) && isset($wp_query->post->ID) && !empty($wp_query->post->ID)){
$current_page_ID = $wp_query->post->ID;
} else if(function_exists('get_the_id') && !empty(get_the_id())){
$current_page_ID = get_the_id();
}else if(!is_null($post) && isset($post->ID) && !empty($post->ID))
$current_page_ID = $post->ID;
else if( (isset($_GET['action']) && sanitize_text_field($_GET['action']) == 'edit') && $post = ((isset($_GET['post']) && is_numeric($_GET['post'])) ? absint($_GET['post']) : false))
$current_page_ID = $post;
else if($p = ((isset($_GET['p']) && is_numeric($_GET['p'])) ? absint($_GET['p']) : false))
$current_page_ID = $p;
else if($page_id = ((isset($_GET['page_id']) && is_numeric($_GET['page_id'])) ? absint($_GET['page_id']) : false))
$current_page_ID = $page_id;
else if(!is_admin() && $wpdb)
{
$actual_link = rtrim($_SERVER['REQUEST_URI'], '/');
$parts = explode('/', $actual_link);
if(!empty($parts))
{
$slug = end($parts);
if(!empty($slug))
{
if($post_id = $wpdb->get_var(
$wpdb->prepare(
"SELECT ID FROM {$wpdb->posts}
WHERE
`post_status` = %s
AND
`post_name` = %s
AND
TRIM(`post_name`) <> ''
LIMIT 1",
'publish',
sanitize_title($slug)
)
))
{
$current_page_ID = absint($post_id);
}
}
}
}
else if(!is_admin() && 'page' == get_option( 'show_on_front' ) && !empty(get_option( 'page_for_posts' ))){
$current_page_ID = get_option( 'page_for_posts' );
}
return $current_page_ID;
}
This function check all possible cases and return ID of the current page or false on the fail.

Related

Change Woocommerce order status programmatically

I am trying to change order status by some conditionals by using woocommerce_thankyou action.
I created some custom order statuses with plugin:
By using this function - nothing happen, the status remain "in hold" and not changed as wishes:
/*after order done*/
function check_and_change_status($order_id){
if ( is_checkout() && is_order_received_page() ) {
$order = wc_get_order( $order_id );
$order_status = $order->get_status();
$product_in_order = false;
$items = $order->get_items();
$count = 0;
foreach ( $items as $item ) {
$product_id = $item->get_product_id();
$is_start_from_product = the_feild('get_an_offer', $product_id);
$the_startFromPrice = the_feild('startFromPrice', $product_id);
$the_winningPrice = the_feild('winningPrice', $product_id);
if ($is_start_from_product && $count == 0) {
$count++;
$price_that_paid = $item->get_total();
if($price_that_paid > $the_startFromPrice && $price_that_paid < $the_winningPrice){
$order->update_status('auctionpending');
}elseif($price_that_paid > $the_winningPrice){
$order->update_status('auctionwon');
}
}elseif ($is_start_from_product && $count > 0) {
/*Do it later*/
}
}
}
}
add_action('woocommerce_thankyou','check_and_change_status');
What i am missing?
The conditional are work well (I have been debugged that), but the order status not changed.
You use the_feild in your foreach loop.
The wordpress function is the_field.
the_field($selector, [$post_id], [$format_value]);
Where $selector is your field name and [$post_id] is the place where your value is saved.
Edit that and try again
$is_start_from_product = the_field('get_an_offer', $product_id);
$the_startFromPrice = the_field('startFromPrice', $product_id);
$the_winningPrice = the_field('winningPrice', $product_id);

Using if template equals in a WordPress function

I am working with this function:
if ( $id && $post && $post->post_type == 'business-areas' )
{
$pieces = explode(' ', $the_title);
$last_word = trim(strtolower(array_pop($pieces)));
if($last_word != 'jobs')
{
$the_title = $the_title . ' jobs';
}
}
return $the_title;
This is basically appending the word JOBS to any titles on a custom post type of business-areas if the last word of the title is not JOBS.
Is there a way to add a template query to this?
So basically, if the page template of the custom post is DEFAULT, do this, if the page template is not DEFAULT, don't do it.
Put this code in the functions.php file.
function add_label_to_post_title( $the_title = '' ) {
global $post;
if ($post && $post->post_type == 'business-areas' )
{
$pieces = explode(' ', $the_title);
$last_word = trim(strtolower(array_pop($pieces)));
if($last_word != 'jobs')
{
$the_title = $the_title . ' jobs';
}
}
return $the_title;
}
add_filter( 'the_title', 'add_label_to_post_title' );

Custom post type url rewriting

I am rewriting the url of CPT 'entertainment' to /entertainment/%year%/%monthnum%/%post_id%/ It is re-writing but gives 404 not found error. How can I solve this?
Here is my code:
add_action( 'init', 'my_rewrite');
function my_rewrite() {
global $wp_rewrite;
$entertainment_structure = '/entertainment/%year%/%monthnum%/%post_id%/';
$wp_rewrite->add_rewrite_tag("%entertainment%", '([^/]+)', "entertainment=");
$wp_rewrite->add_permastruct('entertainment', $entertainment_structure, false);
flush_rewrite_rules();
}
// Add filter to plugin init function
add_filter('post_type_link', 'entertainment_permalink', 10, 3);
// Adapted from get_permalink function in wp-includes/link-template.php
function entertainment_permalink($permalink, $post_id, $leavename) {
$post = get_post($post_id);
$rewritecode = array(
'%year%',
'%monthnum%',
'%day%',
'%hour%',
'%minute%',
'%second%',
$leavename? '' : '%post_id%',
'%post_id%',
'%category%',
'%author%',
$leavename? '' : '%post_id%',
);
if ( '' != $permalink && !in_array($post->post_status, array('draft', 'pending', 'auto-draft')) ) {
$unixtime = strtotime($post->post_date);
$category = '';
if ( strpos($permalink, '%category%') !== false ) {
$cats = get_the_category($post->ID);
if ( $cats ) {
usort($cats, '_usort_terms_by_ID'); // order by ID
$category = $cats[0]->slug;
if ( $parent = $cats[0]->parent )
$category = get_category_parents($parent, false, '/', true) . $category;
}
// show default category in permalinks, without
// having to assign it explicitly
if ( empty($category) ) {
$default_category = get_category( get_option( 'default_category' ) );
$category = is_wp_error( $default_category ) ? '' : $default_category->slug;
}
}
$author = '';
if ( strpos($permalink, '%author%') !== false ) {
$authordata = get_userdata($post->post_author);
$author = $authordata->user_nicename;
}
$date = explode(" ",date('Y m d H i s', $unixtime));
$rewritereplace =
array(
$date[0],
$date[1],
$date[2],
$date[3],
$date[4],
$date[5],
$post->ID,
$post->ID,
$category,
$author,
$post->ID,
);
$permalink = str_replace($rewritecode, $rewritereplace, $permalink);
} else { // if they're not using the fancy permalink option
}
return $permalink;
}
If I replace $entertainment_structure = '/entertainment/%year%/%monthnum%/%post_id%/'; with $entertainment_structure = '/entertainment/%year%/%monthnum%/%entertainment%/'; it works fine
You aren't supposed to hook init, but either register_activation_hook() it, if its a plugin or use after_switch_theme if its a theme (its important to either deactivate/reactivate the plugin or switch themes in order for your rewrites to apply). <= further read here
You might want to have a read of the rewrite API

How to Check Which level category it is for wordpress?

Let me tell you the scenario first say the structure of the categories in wordpress is like this
Level 1: Top
Level 2: -Nextme_1
Level 3: --Nextme_2
--Nextme_3
Level 4: ---Nextme_4
---Nextme_5
Now I require to check what is the level of the category? Say I catch a category of level 3 so I have to use different template and if its level 4. Then I need to use another template?
Anybody can give me some hint?
Thanks
Rahul
If you don't have many categories you can try to edit their slug from admin, and then in your page you get the category slug this way:
if (is_category()) {
$cat = get_query_var('cat');
$category = get_category($cat);
echo 'your slug is '. $category->slug;
}
Now, when you're editing the categories slugs try naming them after their level: cat-lvl-1, cat-lvl-2. Then in your page you extract the number from category slug using some php string function, and then you check that number:
if ($category->slug == 1 ) {
//load the template for the category of level 1
}
if ($category->slug == 2 ) {
//load the template for the category of level 2
}
and so on.
Later edit:
Try this:
function get_level($category, $level = 0)
{
if ($category->category_parent == 0) {
return $level;
} else {
$level++;
$category = get_category($category->category_parent);
get_level($category, $level);
}
}
if (is_category()) {
$cat = get_query_var('cat');
$yourcat = get_category($cat);
echo get_level($yourcat);
}
You can call the get_ancestors() function to get an array containing the parents of the given object. Then you need to count elements in the result.
function get_the_level($id, $type = 'category') {
return count( get_ancestors($id, $type) );
}
if( is_category() ) {
$level = get_the_level( $cat );
}
elseif( is_product_category() ) {
$level = get_the_level( $wp_query->get_queried_object()->term_id, 'product_cat' );
}
Thanks a lot. This is superb with slight a change the code that you have written is fine but its not returning any value.(i,e the $level) although its calculating correct. A minor change i did and its work fine now with a slight editing of you code given below..
`
function get_level($category, $level = 0)
{
if ($category->category_parent == 0) {
return $level;
} else {
$level++;
$category = get_category($category->category_parent);
return get_level($category, $level);
}
}
if (is_category()) {
$cat = get_query_var('cat');
$yourcat = get_category($cat);
echo get_level($yourcat);
}
`
Thanks #zuzuleinen
I visited this page months back. I came back today, arrow up on the above solution then still went digging. Although it is a good solution, Wordpress often offers better or close.
get_category_parents()
This function does as Rahul has typed basically. It also calls itself which seems the most logical approach and that is why Rahul gets a point from me on this. Do not use $link, return a string of categories, explode() them then count or I suppose we could count the number of times the separator has been used and add 1.
function get_category_parents( $id, $link = false, $separator = '/', $nicename = false, $visited = array() ) {
$chain = '';
$parent = get_term( $id, 'category' );
if ( is_wp_error( $parent ) )
return $parent;
if ( $nicename )
$name = $parent->slug;
else
$name = $parent->name;
if ( $parent->parent && ( $parent->parent != $parent->term_id ) && !in_array( $parent->parent, $visited ) ) {
$visited[] = $parent->parent;
$chain .= get_category_parents( $parent->parent, $link, $separator, $nicename, $visited );
}
if ( $link )
$chain .= ''.$name.'' . $separator;
else
$chain .= $name.$separator;
return $chain;
}

how to customize wordpress internal functions, like adjacent_post_link()

I need to customize the previous_post_link() and next_post_link() on WordPress.
Per example, I want to shrink permalinks like "Top 5 programming languages that you need to learn" to "Top 5 programing...".
The function responsible for creating the link isadjacent_post_link() located at wp-includes/link-template.php
To create a custom adjacent link for posts I can make use of the filter hook next_post_link and previos_post_link;
In the functions.php:
function shrink_previous_post_link($format, $link){
$in_same_cat = false;
$excluded_categories = '';
$previous = true;
$link='%title';
$format='« %link';
if ( $previous && is_attachment() )
$post = & get_post($GLOBALS['post']->post_parent);
else
$post = get_adjacent_post($in_same_cat, $excluded_categories, $previous);
if ( !$post )
return;
$title = $post->post_title;
if ( empty($post->post_title) )
$title = $previous ? __('Previous Post') : __('Next Post');
$rel = $previous ? 'prev' : 'next';
//Save the original title
$original_title = $title;
//create short title, if needed
if (strlen($title)>40){
$first_part = substr($title, 0, 23);
$last_part = substr($title, -17);
$title = $first_part."...".$last_part;
}
$string = '<a href="'.get_permalink($post).'" rel="'.$rel.'" title="'.$original_title.'">';
$link = str_replace('%title', $title, $link);
$link = $string . $link . '</a>';
$format = str_replace('%link', $link, $format);
echo $format;
}
function shrink_next_post_link($format, $link){
$in_same_cat = false;
$excluded_categories = '';
$previous = false;
$link='%title';
$format='%link »';
if ( $previous && is_attachment() )
$post = & get_post($GLOBALS['post']->post_parent);
else
$post = get_adjacent_post($in_same_cat, $excluded_categories, $previous);
if ( !$post )
return;
$title = $post->post_title;
if ( empty($post->post_title) )
$title = $previous ? __('Previous Post') : __('Next Post');
$rel = $previous ? 'prev' : 'next';
//Save the original title
$original_title = $title;
//create short title, if needed
if (strlen($title)>40){
$first_part = substr($title, 0, 23);
$last_part = substr($title, -17);
$title = $first_part."...".$last_part;
}
$string = '<a href="'.get_permalink($post).'" rel="'.$rel.'" title="'.$original_title.'">';
$link = str_replace('%title', $title, $link);
$link = $string . $link . '</a>';
$format = str_replace('%link', $link, $format);
echo $format;
}
add_filter('next_post_link', 'shrink_next_post_link',10,2);
add_filter('previous_post_link', 'shrink_previous_post_link',10,2);
That all I needed to do. Thanks!
the next_post_link() and previous_post_link() function both come with customization options. http://codex.wordpress.org/Function_Reference/next_post_link. After reading that and learning what the acceptable arguments to the function are, Test to see if it is possible to pass a php function to the option, like substr().
<?php next_post_link('%link',substr('%title',20),FALSE);?>
'%link' and '%title' are shortcodes to the post link and title.
Let us know if it works out.

Resources