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;
Related
I wanted to know how to get the information of a widget instance, to be able to get all its information from another widget. Try the Get Widget ID plugin but it returns "temp" as a result and I also tried with this code block:
https://wordpress.stackexchange.com/questions/240327/how-to-access-widget-data-from-outside-widget
But I still get the same result.
My idea is the following:
I am modifying a Wordpress widget so that it selects a static post in order to fulfill the function of a featured post in a digital newspaper ... The widget has already been modified and is already working. That same widget is repeated in several places on my website, that is, I use it several times (each with a different selected post).
My idea is to show the featured posts with that widget (those selected by the editor) and modify another widget, that shows me all the posts except the ones that are selected in those widgets. For that I want to know how to get the instance of said widgets that select the featured post, to be able to get the ID of the selected post in each widget and show all the posts except those that are already as featured posts.
In summary ... I just want to see no news that is selected as featured again.
Clarification: This is not a widget written by me, it is a template that I bought and since it did not have this functionality, I am trying to create it.
I leave the code of my widget, in case it is of any use:
<?php
if ( ! defined( 'ABSPATH' ) ) exit;
add_action('widgets_init', 'seleccion_subtitulo');
function seleccion_subtitulo() {
register_widget('seleccion_subtitulo');
}
class seleccion_subtitulo extends WP_Widget {
/*-----------------------------------------------------------------------------------*/
/* Widget Setup
/*-----------------------------------------------------------------------------------*/
public function __construct() {
$widget_ops = array(
'classname' => 'seleccion_subtitulo',
'description' => esc_html__('Seleccionar noticia con titulo y subtitulo', 'disto')
);
parent::__construct('seleccion_subtitulo', esc_html__('Noticias: Noticia titulo + subtitulo [Estilo 1]', 'disto'), $widget_ops);
}
/*-----------------------------------------------------------------------------------*/
/* Display Widget
/*-----------------------------------------------------------------------------------*/
function widget($args, $instance) {
extract($args);
$featured_post = isset($instance["featured_post"]) ? $instance["featured_post"] : '';
$posts = null;
$args = array(
'p' => $featured_post,
'posts_per_page' => 1,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'ignore_sticky_posts' => true
);
$posts_query = new WP_Query;
$posts = $posts_query->query($args);
$unique_block_id = rand(10000, 900000);
echo '<div class="jl_large_builder jl_nonav_margin jelly_homepage_builder jl-post-block-'.esc_html($unique_block_id).'">';
if (!empty($instance['titles'])) {?>
<div class="homepage_builder_title">
<h2 class="builder_title_home_page">
<?php echo esc_attr($instance["titles"]);?>
</h2>
</div>
<?php }?>
<?php
while ($posts_query->have_posts()) {
$post_id = get_the_ID();
$posts_query->the_post();
$categories = get_the_category(get_the_ID());
?>
<div class="jl_post_title_top jl_large_format">
<h3 class="image-post-title"><a href="<?php the_permalink(); ?>">
<?php the_title()?></a></h3>
</div>
<div class="post-entry-content">
<div class="post-entry-content-wrapper">
<div class="large_post_content">
<p>
<?php echo wp_trim_words( get_the_content(), 34, '...' );?>
</p>
<!-- <div class="jl_large_sw">
<?php echo esc_html__('Read More', 'disto')?>
<?php if(function_exists('disto_share_footer_link')){echo disto_share_footer_link(get_the_ID());}?>
</div> -->
</div>
</div>
</div>
<div class="box jl_grid_layout1 blog_large_post_style">
<?php if ( has_post_thumbnail()) {?>
<div class="jl_front_l_w">
<?php $slider_large_thumb_id = get_post_thumbnail_id();
$slider_large_image_header = wp_get_attachment_image_src( $slider_large_thumb_id, 'disto_slider_grid_large', true ); ?>
<?php if($slider_large_thumb_id){?>
<span class="image_grid_header_absolute" style="background-image: url('<?php echo esc_url($slider_large_image_header[0]); ?>')"></span>
<?php }else{?>
<span class="image_grid_header_absolute"></span>
<?php }?>
<?php if(get_theme_mod('disable_post_category') !=1){
$categories = get_the_category(get_the_ID());
if ($categories) {
echo '<span class="meta-category-small">';
foreach( $categories as $tag) {
$tag_link = get_category_link($tag->term_id);
$title_bg_Color = get_term_meta($tag->term_id, "category_color_options", true);
$title_reactions = get_term_meta($tag->term_id, "disto_cat_reactions", true);
if($title_reactions){}else{echo '<a class="post-category-color-text" style="background:'.$title_bg_Color.'" href="'.esc_url($tag_link).'">'.$tag->name.'</a>';}
}echo "</span>";}}?>
<?php echo disto_post_type();?>
</div>
<?php }?>
<div class="jl_post_title_top jl_large_format">
<?php echo disto_single_post_meta(get_the_ID()); ?>
</div>
</div>
<?php }
if($post_loadmore == 1){echo '<div class="jl-loadmore-btn-w">'.esc_html__('Load more', 'disto').'</div>';
wp_add_inline_script( 'disto-custom', "(function($){ $(document).ready(function() {'use strict'; var current_page_".esc_js($unique_block_id)." = 1; $('.jl-post-block-".esc_js($unique_block_id)." .jl_btn_load').click(function(e){ e.preventDefault(); e.stopPropagation(); var button = $(this), data = {'action': 'jl_post_more','query': ".json_encode( $posts_query->query_vars , true).",'page' : current_page_".esc_js($unique_block_id).",'cat' : '".esc_js($cats)."','jl_layout' : 'postslarge'}; var button_default_text = button.text(); $.ajax({ url : '".esc_url(site_url())."/wp-admin/admin-ajax.php', data : data, type : 'POST', beforeSend : function ( xhr ) {button.text('');button.addClass('btn-loading'); }, success : function( data ){ if( data ) { button.text( button_default_text ); button.removeClass('btn-loading'); $('.jl-post-block-".esc_js($unique_block_id)." .jl-loadmore-btn-w').before(data); current_page_".esc_js($unique_block_id)."++; if ( current_page_".esc_js($unique_block_id)." == ".esc_js($posts_query->max_num_pages)." ) button.remove(); }else {button.remove();}}});});});})(jQuery);");
}
wp_reset_postdata();
?>
</div>
<?php }
/*-----------------------------------------------------------------------------------*/
/* Update Widget
/*-----------------------------------------------------------------------------------*/
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['featured_post'] = $new_instance['featured_post'];
return $instance;
}
/*-----------------------------------------------------------------------------------*/
/* Widget Settings (Displays the widget settings controls on the widget panel)
/*-----------------------------------------------------------------------------------*/
function form( $instance ) {?>
<h2>Elige una de las ultimas 20 noticias para establecerla como portada secundaria.</h2>
<div class="container">
<p>
<label>
<strong> <?php esc_html_e('Seleccionar noticia destacada:', 'disto');?></strong>
</label>
</p>
<p>
<select id="<?php echo esc_attr( $this->get_field_id( 'featured_post' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'featured_post' ) ); ?>">
<?php
$posts_args = array('posts_per_page' => 20,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'ignore_sticky_posts' => true);
$last_entries = get_posts($posts_args);
foreach ($last_entries as $entry) {
?>
<option value="<?php echo $entry->ID; ?>" <?php if($instance['featured_post']==$entry->ID){ echo 'selected="selected"'; } ?> ><?php echo $entry->post_title; ?></option>
<?php
}
?>
</select>
</p>
</div>
<?php
}
}
?>
If I do var_dump ($instance) it shows me the following:
array(3) { ["featured_post"]=> string(4) "2970" ["so_sidebar_emulator_id"]=> string(29) "seleccion_subtitulo-421210000" ["option_name"]=> string(26) "widget_seleccion_subtitulo" }
I estimate that the following value tells me the ID of my widget instance:
["so_sidebar_emulator_id"] => string (29) "seleccion_subtitulo-421210000"
but I don't know how to invoke it from another widget, to get the information from it.
When obtaining that information, I try the following code to see what I get (I saw this code in the link that happens first):
$widget_name = 'seleccion_subtitulo';
$widget_instance = '421210000';
$widget_instances = get_option('widget_' . $widget_name);
$data = $widget_instances[$widget_instance];
var_dump($widget_instances);
If I do var_dump($data); I get NULL
If I do var_dump($widget_instances); I get:
array(1) { ["_multiwidget"]=> int(1) }
Lets rephrase your question into 2 parts:
"How to get a widgets settings"
"How to get the list of featured posts as used by that widget for purpose of excluding them from another list of posts"
1. Widget settings:
Widget settings are stored in the database in the wp_options table. If you do a search in phpmyadmin using widget% wildcard in the option name field you will see all widgets and their serialised data arrays.
You may note that they all have a subarray called "_multiwidget" which will contain the instances and their settings. In your example above you dumped this ["_multiwidget"]=> int(1)
This shows that nothing has yet been stored for that widget. The widget is not in a sidebar and/or no featured posts have been defined for that widget.
If the widget had been saved to a sidebar with some settings we would be seeing more details here.
Setup some widget instances so you can see the saved data structures. Then you will be able to see the widget details (either via phpmyadmin or by dumping as before)
2. Get list of featured posts out of a set of widget instances in order to exclude them from a query (in another widget)
For the widget you looking at we would probably see an array of settings one of which would be called "featured_post".
Once the widget has been dragged to some sidebars and has some featured posts defined in a few instances, you can then in your new widget do something like (pseudo code):
$widget_name = 'seleccion_subtitulo'; //if that's the widget name in the db.
$widget_settings = get_option('widget_' . $widget_name);
$featured_posts = array();
if (!empty($widget_settings)) {
if (!empty($widget_settings["_multiwidget"])) {
$instances = $widget_settings["_multiwidget"];
foreach ( $instances as $wid => $instance) {
$featured_posts[] = $instance['featured_post']; // if that is how it is stored in the widget details
}
}
}
You can then use https://developer.wordpress.org/reference/functions/get_posts/ and pass the array $featured_posts
in the argument array as
'exclude' => $featured_posts
Note that It is not necessary to know the 'instance' or the 'widget id' for what you say to want to achieve, one simply has to loop through all the instances for that widget.
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.
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');
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;
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).