Access the post data via short code (Visual Composer post grid) - php

I am using a Visual Composer (Post Grid) element, with a custom template.
I'd like to output the post id via a shortcode, so I've created a simple shortcode:
function myshortcode_title( ){
return get_the_ID();
}
add_shortcode( 'page_title', 'myshortcode_title' );
but it doesn't seem to retrieve the post ID. I am adding it to the grid via a Text block.
The shortcode works on any other page, but not inside the VC post grid.
How else can I access the post ID inside the post grid?
Thanks in advance! Here is a screenshot of the element.

I now it's late but I had the same problem and this answer can help other people.
You need to use the global $post in your function.
Exemple of usage:
function my_function_shortcode()
{
global $post; // important !
$args = array(
'post_type' => 'event',
'post_status' => 'publish',
);
$event_query = new WP_Query($args);
if ($event_query->have_posts()) : while ($event_query->have_posts()) : $event_query->the_post();
$event_location = get_post_meta($post->ID, 'event_location', true);
endwhile;
endif;
wp_reset_query();
}
add_shortcode('my_function_output', 'my_function_shortcode');

Related

Editing the page does not work if I use get_template_part in shortcode

Help solve the problem, please!
I have template part content-event.php. I use it in the loop of custom post type "event" in archive-event.php It works well here.
Now I need to make a carousel of these posts (events). My code in functions.php:
add_shortcode('km_events_carousel', 'km_events_carousel');
function km_events_carousel(){
$html = '<div class="your-class">';
$args = array(
'post_type'=> 'km_event',
'meta_key' => 'start',
'orderby' => 'meta_value_num',
'order' => 'ASC'
);
$km_events_query = new WP_Query( $args );
if( $km_events_query->have_posts() ) {
while ( $km_events_query->have_posts() ) {
ob_start();
get_template_part( kettlebell_get_post_template_part_slug(), 'event' );
$html .= ob_get_clean();
}
}
$html .= '</div>';
wp_reset_postdata();
return $html;
}
This shortcode also works well.
The essence of the problem: when I click on the "Edit page" on the top of the page or open the page from the admin panel for editing, I get a picture of one of the posts that appear in the carousel instead of the admin panel.
If I comment function get_template_part() - all works correctly. But of course, then I do not get posts in the carousel.
Tell me, please, what could be the error or some workaround.

How to alter Wordpress global post title using php

I know i can use:
global $wp_query;
$wp_query->is_page = true;
For example to set the global is_page conditional to true.
Can i change the global post title in a similar way so it would effect the the_title() returned value?
To clarify things:
I need for a use of a "virtual page" case, where no post is actually loaded and i don't want to use any existing post title. just inject some custom title to the current globals so i will get it when using the_title on the current page.
To modify the title you can use a build in hook of wordpress:
function suppress_if_blurb( $title, $id = null ) {
if ( in_category(' blurb', $id ) ) {
return '';
}
return $title;
}
add_filter( 'the_title', 'suppress_if_blurb', 10, 2 );
https://codex.wordpress.org/Plugin_API/Filter_Reference/the_title
Finally found it. gladly it's very simple :) but this piece of code will also create all other post vars for a "fake post/page":
$post_id = -99; // negative ID, to avoid clash with a valid post
$post = new stdClass();
$post->ID = $post_id;
$post->post_title = 'Some title or other';
$wp_post = new WP_Post( $post );
wp_cache_add( $post_id, $wp_post, 'posts' );
global $wp, $wp_query;
$wp_query->post = $wp_post;
$wp_query->posts = array( $wp_post );
$wp_query->queried_object = $wp_post;
$wp_query->queried_object_id = $post_id;
$wp_query->is_404=false;
$wp_query->is_page=true;
$GLOBALS['wp_query'] = $wp_query;
$wp->register_globals();
More details here!

Wordpress Custom Function in Plugin to Return Post ID from Specified Category

Hoping you can help me figure out why I can't get get_first_post_in_category to successfully return a usable post ID. At the moment I am using the Wordpress Plugin Boilerplate to create a plugin that removes the first post of a specified category (through the admin options page) from the primary loop. All is well until I try and programmatically retrieve the post ID.
Here I define my hook (works fine):
// In private function define_public_hooks()
$this->loader->add_action( 'pre_get_posts', $plugin_public, 'exclude_featured_post_pre_injection');
Here is the callback function I am using to exclude a specific post from the main query. If $first_post_in_category_id is manually set, it works perfectly. If I try and set it to " = get_first_post_in_category();" I am thrown a 500 error.
public function exclude_featured_post_pre_injection($query){
// Doesn't work
$first_post_in_category_id = $this->get_first_post_in_category();
//Works
// $first_post_in_category_id = '427';
if ($query->is_home() && $query->is_main_query()) {
$query->set('post__not_in', array($first_post_in_category_id));
}
}
And here is the issue ::: this function I am attempting to just return the ID of the first post in the category to be used in other action/filter callbacks. If I call this, it returns a 500 error.
public function get_first_post_in_category(){
$cat_id = get_option('sticky_content_category_id');
// currently returns (string) '3' which has posts in it
$args = array(
'posts_per_page' => 1,
'cat' => $cat_id
);
$latest_cat_post = new WP_Query($args);
while ( $latest_cat_post->have_posts() ) : $latest_cat_post->the_post();
$first_post_id = the_ID();
endwhile;
wp_reset_postdata();
return $first_post_id;
}
Any idea on the best way to resolve the issues I am running into?
I cant see how it can cause an error 500 but the code below works for me.
$category_id = get_cat_ID('Wordpress');
//echo $category_id;
$args = array(
'posts_per_page' => 1,
'cat' => $category_id,
'orderby' => 'ID',
'order' => 'DESC'
);
$query = new WP_Query($args);
while($query->have_posts()):$query->the_post();
echo the_ID();
endwhile;

Call a function in function.php Wordpress

I'm studying PHP and have a basic question,
I have this code in the page portfolio.php
<?php
$args = array(
'post_type' => 'portfolio',
'orderby' => 'menu_order',
'order' => 'ASC',
'posts_per_page' => -1
);
$portfolio_query = new WP_Query($args);
if( $portfolio_query->have_posts() ) :
echo '<div id="primary" class="hfeed">';
while( $portfolio_query->have_posts() ) : $portfolio_query->the_post();
// project url
$portfolio_url = get_post_meta($post->ID, '_zilla_portfolio_project_url', true);
if( !empty($portfolio_url) )
$portfolio_button_copy = get_post_meta($post->ID, '_zilla_portfolio_project_url_copy', true);
?>
I would like to echo $portfolio_url in my function.php
Any reference for more study in this case would be appreciated.
It's not clear what you're trying to do, but if you need to pass a url to a function then you can do so with an argument:
function your_function($url) {
// Do whatever you want with $url here, like:
echo 'A link';
}
You can save the above into functions.php.
Based on your comments, I think what you're trying to do is take your code in portfolio.php and turn it into a function that you can call elsewhere. In that case you need to actually define it as a function:
function get_portfolio_url() {
// Insert your existing code in here...
// Then you can either echo $portfolio_url:
echo $portfolio_url;
// Or you can just return it if you plan on doing other things with it
return $portfolio_url
}
You can insert the above function into functions.php. Then you can call it anywhere with get_portfolio_url(). Technically you would no longer require portfolio.php, since you've created a function that does exactly the same thing. Be aware that you don't need to create separate PHP files for every function you require; you can just define them as separate functions in one location and then call them as necessary (which is essentially what functions.php is for in WordPress; a single file to hold all the functions your theme uses).

$post is null while in the loop

According to WP documentation this can't be happening but it is:
http://codex.wordpress.org/The_Loop
You can display other information about each post using the
appropriate Template Tags or (for advanced users) by accessing the
$post variable, which is set with the current post's information while
The Loop is running.
All following code examples use $post to access the current post but I can't. Even though it goes in the loop $post is null:
$args = array('post_type' => 'carousel_bootstrap', 'posts_per_page' => 10);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
var_dump($post->ID);//=NULL
$title=the_title(null,null,false);
var_dump($title);//string(4) "NOPE"
....
endwhile;
wp_reset_postdata();
So either $post should not be null or the var_dump should not execute in the loop. I need to access this current post's custom fields but can't do it if $post is null. To make it more confusing; in the next line the $title variable is set to the current post's title.
How would I go about solving this? Using word press 3.6.1
[UPDATE]
I made a custom post called carousel, thought I'd use it to contain the html code for a twitter bootstrap carousel. In header I'm calling a function that checks if a custom carousel post exist with a certain name (provided by a custom value from the page).
In the header $post is the page, in the function checking the custom post the $post is null and when exiting the function and continuing in the header $post is the custom post (no longer the page).
Seemed like a good idea to do it this way when I started but looks like it can't be done this way.
The right way to get the post id in a custom WP_QUERY is: $loop->post->ID
$args = array('post_type' => 'carousel_bootstrap', 'posts_per_page' => 10);
$loop = new WP_Query($args);
global $post;
while ($loop->have_posts()) : $loop->the_post();
$loop->post->ID; //This is how you get the id $post will not work unless you
setup_postdata( $loop->post->ID );
print_r($post->ID); //now works.
endwhile;
wp_reset_postdata();
Got it doing what it does but think the code could use some improvement:
(added on blankslate)
In /wp-content/themes/blankslate/functions.php
//only using single carousel per page now
$vars=array('carouselHtml'=>'<div style="h'.
'eight:100px"><h1>Working, no Carousel</h1></div>',
'css'=>[],
'js'=>[]
);
function getInits(){
global $vars;
return $vars;
}
function setInits() {
global $post;
global $vars;
//see if the page specified a carousel (if value it's the title)
$carousel = get_post_meta($post->ID, 'carousel', true);
//collect all custom fields named "js" usually to fix screen
//re sizing like hiding images or big sliders
$scriptItems = get_post_meta($post->ID, 'js', false);
if ($scriptItems) {
foreach ($scriptItems as $item) {
$vars["js"][]=$item;
}
}
//load all custom fields of the page named css
//can be used for specific styles for the page
$cssItems = get_post_meta($post->ID, 'css', false);
if ($cssItems) {
foreach ($cssItems as $item) {
$vars["css"][]=$item;
}
}
//page has a custom field value named carousel
//it contains the title of the custom post that
//should contain the html, css and js
if ($carousel) {
//nice and intuitive query, gotta love it
$args = array('post_type' =>
'carousel_bootstrap',
'title' => $carousel,
'posts_per_page' => 100);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
$title=the_title(null,null,false);
if($title===$carousel){
//found the custom carousel post, load html
//and add css js not to the page because css
//goes in the top and js goes in the bottom
$tmp=get_post_meta($post->ID, 'js', true);
if($tmp){$vars["js"][]=$tmp;}
$tmp=get_post_meta($post->ID, 'css', true);
if($tmp){$vars["css"][]=$tmp;}
$vars["carouselHtml"]=$post->post_content;
break;
}
endwhile;
//$post was the page at the start of the function
//now it could be the carousel post, not sure
//if the following is needed but works either
//with or without it
wp_reset_postdata();
}
}
//creating custom post named carousel
add_action('init', 'create_carousel_post_type');
function create_carousel_post_type() {
register_post_type( 'carousel_bootstrap', array(
'labels' => array(
'name' => __('Carousels'),
'singular_name' => __('Carousel')
),
'public' => false,
'has_archive' => true,
'rewrite' => array('slug' => 'carousels'),
'show_ui' => true,
'menu_position' => 5,
'supports' => array('title','editor','author',
'thumbnail','custom-fields','revisions')
));
}
In /wp-content/themes/blankslate/page.php
setInits();
get_header();
....
<body <?php body_class(); ?> id="top">
<!-- Carousel
based on http://getbootstrap.com/2.3.2/examples/carousel.html
================================================== -->
<div id="myCarousel" class="carousel slide">
<div class="carousel-inner">
<?php
$vars=getInits();
echo $vars["carouselHtml"];
?>
In /wp-content/themes/blankslate/header.php
$vars=getInits();
//output collected css
foreach ($vars["css"] as $item) {
echo '<link rel="stylesheet" type="text/css" href="'.$item.'" />';
}
The footer has same sort of code but for JavaScripts.
$args = array('post_type' => 'carousel_bootstrap', 'posts_per_page' => 10);
$loop = new WP_Query($args);
if($loop->have_posts()): while($loop->have_posts()): $loop->the_post();
//echo the title
the_title();
the_content();
//get the ID
$postId = get_the_ID();
endwhile;
endif;

Categories