Trying to get my post meta from posts using shrotcodes and then displaying it on the content.This is the code that's trying to do this:
$string = '';
$custom_content = get_post_custom($post->ID);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
$content = get_the_content();
$bonus = $custom_content["bonus"];
$string .= $content . $bonus . '<br>';
endwhile;
}
return $string;
It's not working as the custom content returns empty. Whats wrong? Thanks in advance
I don't think you got the shortcode idea, you should read some info about add_shortcode() also you can use get_post_meta() to retriev the metadata from the database.
Here is an example on how you can achieve this but this will only work with the main loop (as default):
<?php
//you can put this code in functions.php or you can build a plugin for it
function metadata_in_content($attr) {
//this is the function that will be triggerd when the code finds the proper shortcode in the content; $attr is the parameter passed throw the shortcode (leave null for now)
global $wpdb, $wp_query;
//we need global $wpdb to query the database and to get the curent post info
if (is_object($wp_query->post)) {
$post_id = $wp_query->post->post_id;// here we save the post id
$metadata = get_post_meta( $post_id, $key, $single ); // here we get the needed meta, make sure you place the correct $key here, also if you don't want to get an array as response pass $single as "true"
return $metadata; // this finally replaces the shortcode with it's value
}
}
add_shortcode('insert_metadata', 'metadata_in_content');
//the above code hooks the metadata_in_content function to the [insert_metadata] shortcode
?>
Now all it's left to do is to place [insert_metadata] in the post content and things should work.
I recently needed to change my permalink structure in Wordpress. However the change caused all my social sharing counters to reset. I found this great script which I modified below, http://encosia.com/preserving-social-sharing-counters-through-a-url-change/. I rewrote it so it would remove the %poste-id% at the end of the url on older posts.
The problem is that for the most part this works, however I need it to call the permalink category not the first category in the get_the_category(); array. Is there anyway I can pull this info, or modify this script to work that way? This is also being used in the loop. Thanks!!
<?php
$url_change_id = 68135;
$postid = $post->ID;
$category = get_the_category();
$slug = $post->post_name;
$permalink_url = get_permalink();
if (intval($postid) < $url_change_id) {
$url_date_prefix = "/" . $category[0]->category_nicename .
"/" . $slug .
".html";
$sharing_url = str_replace($permalink_url,
"http://website.com" . $url_date_prefix,
$permalink_url);
} else {
$sharing_url = get_permalink();
}
?>
<?php echo $sharing_url; ?>
For some reason, I cannot get WP_Query to return the custom field values of posts. I can get the post thumbnails using get_the_post_thumbnail($post->ID, array(50,50)), but I cannot get the custom field data using get_post_meta($post->ID, $key, true).
A stripped-down version of what I'm trying to do:
<?php
$keys = array('Show Date','Birth Year','Origin');
echo '<table>';
echo '<tr><th>Title</th>';
foreach( $keys as $key ) {
echo '<th>' . $key . '<th>';
}
echo '</tr>';
$myquery = new WP_Query( 'post_type=post' );
if( $myquery->have_posts() ) : while( $myquery->have_posts() ) : $myquery->the_post();
$title = get_the_title();
echo '<tr><td>' . $title . '</td>';
$values = array();
foreach( $keys as $key ) {
$values[] = get_post_meta($post->ID, $key, true);
}
foreach( $values as $value ) {
echo '<td>';
echo $value;
echo '</td>';
}
echo '</tr>';
endwhile; endif;
echo '</table>';
?>
Also available here:
http://pastebin.com/at8S2THs
Even with all non-essential code removed, I cannot make this work. I know you can use parameters like meta_key and meta_value in a query to narrow down the results, but I just want to display all values for the keys I specify, if they exist, for each post.
Any help would be greatly appreciated...
** SOLUTION FOUND **
Just needed to add global $post; after the start of the loop. Thanks to #Kimikaze on the WP support forum for providing the solution!
When I can't find the data I need in wordpress, I always find it helpful to print the Global $post object to screen, so I can see if my data is making it to the page.
Global $post;
echo "<pre>";
print_r($post);
echo "</pre>";
All the helper methods or "hooks" are usually just interacting with this (or another) global object. Check the output of this on $post (and maybe your $values array) for data you're looking for and if it's there, you can just reffer to it directly, like the post title for example
$post->title
Another thought, The third parameter of get_post_meta() makes it return a single string when set to true, what do you get when it's set to false?
I'm guessing the problem has to do with the values you're using as meta keys. To retrieve the data with get_post_meta() you'll want to pass in the actual meta_key values, which are probably 'show_date', 'birth_year', and 'origin' since the meta_key value doesn't handle uppercase letters or spaces. Try changing to those values where you're setting the $keys array:
$keys = array('show_date','birth_year','origin');
If that doesn't work, it might be worth checking in the database (in the wp_postmeta table) to confirm the actual meta_key values.
I need to query a category in home page. in index.php file I used this script
$all_featured_posts = query_posts(array('category_name'=>'featured-programs'));
Then in the header.php file I need to change the title
<title>
<?php
if ( is_home() ) {
echo 'My site name' ;
} elseif (is_404()) {
echo '404 Not Found';
} elseif (is_category()) {
echo ' Category' . wp_title('',0).' | My site name' ;
}
?>
The problem is when I query a category in the index file then the is_home return false ( Tried with is_front_page() also ) Then it alway show the title with the name of the category which I query.
How I can fix it? Thanks you!
I might be wrong, but I think because you use query_posts(), all your is_* functions change their values. And, well, because you do query a category, is_home() should return false.
What you can do to solve it, is use new WP_Query(), and get all the posts from it. This way, you will not be affecting the original WP_Query, and thus the is_* functions.
The code should look like this:
$query = new WP_Query('category_name=featured-programs');
while ( $query->have_posts() ) : $query->the_post();
echo '<li>';
the_title();
echo '</li>';
endwhile;
// Reset Post Data
wp_reset_postdata();
What PHP code can be used to retrieve the current page name in a WordPress theme?
All the solutions I have seen so far:
the_title()
get_page()->post_name
get_post()
etc.
But these don't work for a page that contains post entries. They will all return the name of the latest blog entry.
Stated another way, assume that you have a page created in WordPress with the name "My News". This page is set as the "post page". Add a couple of posts to the page.
Now, what API can be used to retrieve the string "my-news" instead of the name of the latest post?
I've found the following variable which seems to work.
$wp_query->queried_object->post_name
This is actually the URL friendly version of the page name (slug), which is what I was looking for too. This was tested with the default template (Twenty Ten). I'm really not sure why the two variables given below do not work on my site. Thanks to keatch for the print_r() tip.
Now, why is this information hidden so deep down?
The WordPress global variable $pagename should be available for you. I have just tried with the same setup you specified.
$pagename is defined in the file wp-includes/theme.php, inside the function get_page_template(), which is of course is called before your page theme files are parsed, so it is available at any point inside your templates for pages.
Although it doesn't appear to be documented, the $pagename var is only set if you use permalinks. I guess this is because if you don't use them, WordPress doesn't need the page slug, so it doesn't set it up.
$pagename is not set if you use the page as a static front page.
This is the code inside /wp-includes/theme.php, which uses the solution you pointed out when $pagename can't be set:
--
if ( !$pagename && $id > 0 ) {
// If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object
$post = $wp_query->get_queried_object();
$pagename = $post->post_name;
}
My approach to get the slug name of the page:
$slug = basename(get_permalink());
<?php wp_title(''); ?>
This worked for me.
If I understand correctly, you want to get the page name on a page that has post entries.
Ok, you must grab the page title before the loop.
$page_title = $wp_query->post->post_title;
Check for the reference: http://codex.wordpress.org/Function_Reference/WP_Query#Properties.
Do a
print_r($wp_query)
before the loop to see all the values of the $wp_query object.
You can get the current page, post, or custom post type with the global variable $post:
echo $post->post_title
Note: In a function or class you'll need to specify global $post; prior to trying to use $post.
If you have loops on your page, make sure you end each loop with wp_reset_postdata(); to set $post back to the default item being displayed (the page).
Note, the 'post_title' variable is also available for any custom loop / query... including menu items and media attachments... everything in WordPress is a 'post'.
We just need to use the "post" global variable:
global $post;
echo $post->post_title;
This will echo the current page/post title.
If you're looking to access the current page from within your functions.php file (so, before the loop, before $post is populated, before $wp_query is initialized, etc...) you really have no choice but to access the server variables themselves and extract the requested page from the query string.
$page_slug = trim( $_SERVER["REQUEST_URI"] , '/' )
Note that this is a "dumb" solution. It doesn't know, for instance that the page with the slug 'coming-soon' is also p=6. And it assumes that your permalink settings are set to pagename (which they should be anyway!).
Still, can be a useful little trick if you have a controlled scenario. I'm using this in a situation where I wish to redirect non-logged in visitors to a "coming soon" page; but I have to make sure that I'm not throwing them into the dreaded "redirect loop", so I need to exclude the "coming soon" page from this rule:
global $pagenow;
if (
! is_admin() &&
'wp-login.php' != $pagenow &&
'coming-soon' != trim( $_SERVER["REQUEST_URI"] , '/' ) &&
! is_user_logged_in()
){
wp_safe_redirect( 'coming-soon' );
}
I believe that the Roots starter theme has a fantastic function to get the current page title. It is very hackable, covers all bases, and can be easily used with the wp_title hook.
/**
* Page titles
*/
function roots_title() {
if (is_home()) {
if (get_option('page_for_posts', true)) {
echo get_the_title(get_option('page_for_posts', true));
} else {
_e('Latest Posts', 'roots');
}
} elseif (is_archive()) {
$term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy'));
if ($term) {
echo $term->name;
} elseif (is_post_type_archive()) {
echo get_queried_object()->labels->name;
} elseif (is_day()) {
printf(__('Daily Archives: %s', 'roots'), get_the_date());
} elseif (is_month()) {
printf(__('Monthly Archives: %s', 'roots'), get_the_date('F Y'));
} elseif (is_year()) {
printf(__('Yearly Archives: %s', 'roots'), get_the_date('Y'));
} elseif (is_author()) {
$author = get_queried_object();
printf(__('Author Archives: %s', 'roots'), $author->display_name);
} else {
single_cat_title();
}
} elseif (is_search()) {
printf(__('Search Results for %s', 'roots'), get_search_query());
} elseif (is_404()) {
_e('Not Found', 'roots');
} else {
the_title();
}
}
Try this:
$pagename = get_query_var('pagename');
I have come up with a simpler solution.
Get the returned value of the page name from wp_title(). If empty, print homepage name, otherwise echo the wp_title() value.
<?php $title = wp_title('', false); ?>
Remember to remove the separation with the first argument and then set display to false to use as an input to the variable. Then just bung the code between your heading, etc. tags.
<?php if ( $title == "" ) : echo "Home"; else : echo $title; endif; ?>
It worked a treat for me and ensuring that the first is declared in the section where you wish to extract the $title, this can be tuned to return different variables.
Use:
$title = get_the_title($post);
$parent_title = get_the_title($post->post_parent);
echo $title;
echo $parent_title;
This seems to be the easiest to use:
<?php single_post_title(); ?>
One option, if you're looking for the actual queried page, rather than the page ID or slug is to intercept the query:
add_action('parse_request', 'show_query', 10, 1);
Within your function, you have access to the $wp object and you can get either the pagename or the post name with:
function show_query($wp){
if ( ! is_admin() ){ // heck we don't need the admin pages
echo $wp->query_vars['pagename'];
echo $wp->query_vars['name'];
}
}
If, on the other hand, you really need the post data, the first place to get it (and arguably in this context, the best) is:
add_action('wp', 'show_page_name', 10, 1);
function show_page_name($wp){
if ( ! is_admin() ){
global $post;
echo $post->ID, " : ", $post->post_name;
}
}
Finally, I realize this probably wasn't the OP's question, but if you're looking for the Admin page name, use the global $pagenow.
Within the WordPress Loop:
if ( have_posts() ) : while ( have_posts() ) : the_post();
/******************************************/
echo get_the_title();
/******************************************/
endwhile; endif;
This will show you the current page title.
For reference: get_the_title()
Here's my version:
$title = ucwords(str_replace('-', ' ', get_query_var('pagename')));
get_query_var('pagename') was just giving me the page slug. So the above replaces all the dashes, and makes the first letter of each word uppercase - so it can actually be used as a title.
Show the title before the loop starts:
$page_title = $wp_query->post->post_title;
This is what I ended up using, as of 2018:
<section id="top-<?=(is_front_page() ? 'home' : basename(get_permalink()));?>">
I've now found this function on WordPress Codec,
get queried
which is a wrapper for $wp_query->get_queried_object.
This post put me in the right direction, but it seems that it needs this update.
This also works if you are in the functions.php. It is not the best approach since you have to use the global array, but it works.
First, we need to add a filter. There must exist a better filter to use than the template_include, but I don't know all of them. Please point me to the right one.
add_filter( 'template_include', 'var_template_include', 1000 );
function var_template_include( $template ){
global $wp_query;
$GLOBALS['current_page'] = $wp_query->get_queried_object()->post_name;
return $template;
}
Avoid using the variable directly
function get_current_page( $echo = false ) {
if( !isset( $GLOBALS['current_page'] ) )
return false;
return $GLOBALS['current_page'];
}
Now you can use the function get_current_page() in any other part of the functions.php.