I'm using WP_Query to get posts from a custom post type to use the result in a metabox. Everything works great with my query. But after this query I can't get the other meta values from database.
This is my helper function to get custom field value:
function my_page_get_custom_field( $value ) {
global $post;
$custom_field = get_post_meta( $post->ID, $value, true );
if ( !empty( $custom_field ) )
return is_array( $custom_field ) ? stripslashes_deep( $custom_field ) : stripslashes( wp_kses_decode_entities( $custom_field ) );
return false;
}
Here's my query:
$sliderArgs = array(
'posts_per_page' => -1,
'post_type' => 'slider',
);
$slider = new WP_Query($sliderArgs);
if ($slider->have_posts()) {
?>
<select name="slider" id="slider">
$selectedSlide = my_page_get_custom_field('slider');
while($slider->have_posts()){
$slider->the_post();
$slideID = get_the_ID();
?><option value="<?php echo $slideID; ?>" <?php selected($selectedSlide, $slideID, true); ?>><?php the_title(); ?></option><?php
}
wp_reset_postdata(); ?>
</select>
}
And this is my other custom field which returns empty (there is a value in database and when I try to change it works great but not displaying in input value in admin):
<input type="text" name="meta_title" id="meta_title" value="<?php echo my_page_get_custom_field('meta_title'); ?>">
OK I solved it.
I used get_posts instead of WP_Query. This helped me a lot: https://core.trac.wordpress.org/ticket/18408#comment:5
Related
I have two custom post types set up - "Books" and "Authors". I am using custom metadata which allows you to link a book to an author via a select box (by querying posts from the authors post type to create the select options).
This works fine, but I'm also trying to create a custom filter on the posts screen for the books post type that allows you to filter by author, which isn't behaving as expected. Here's the code I'm using to add the filter:
function book_filter() {
global $typenow;
global $wp_query;
if ( $typenow == 'book' ) {
$authors = new WP_Query(
array(
'post_type' => 'author',
'nopaging' => true
)
);
wp_reset_postdata();
/*
$authors = get_posts( array(
'post_type' => 'author',
'numberposts' => -1
));
*/
$current_author = '';
if( isset( $_GET['author'] ) ) {
$current_author = $_GET['author'];
} ?>
<select name="author" id="author">
<option value="all" <?php selected( 'all', $current_author ); ?>>All authors</option>
<?php
if ($authors->have_posts()) {
while ($authors->have_posts()) {
$authors->the_post();
if ($current_author == get_the_ID()) {
echo '<option value="' . get_the_ID() . '" selected>' . get_the_title() . '</option>';
} else {
echo '<option value="' . get_the_ID() . '">' . get_the_title() . '</option>';
}
}
}
/* foreach( $authors as $author ) { ?>
<option value="<?php echo $author->ID; ?>" <?php selected( $author->ID, $current_author ); ?>><?php echo get_the_title($author->ID); ?></option>
<?php } */
?>
</select>
<?php }
}
add_action( 'restrict_manage_posts', 'book_filter' );
function do_book_filter( $query ) {
global $pagenow;
$post_type = isset( $_GET['post_type'] ) ? $_GET['post_type'] : '';
if ( is_admin() && $pagenow=='edit.php' && $post_type == 'book' ) {
if (isset( $_GET['author'] ) && $_GET['author'] !='all' ) {
$query->query_vars['meta_key'] = 'author';
$query->query_vars['meta_value'] = $_GET['author'];
$query->query_vars['meta_compare'] = '=';
}
}
}
add_filter( 'parse_query', 'do_book_filter' );
Initially, all the authors are shown in the filter, and selecting an author to filter by does actually work. The problem is that, once it's been filtered, the authors disappear from the select box dropdown. I tried adding an else statement to if ($authors->have_posts()) {... and this confirmed that it isn't fetching posts from the authors post type after a filter has been set.
I'm also using another custom filter (removed from the code for simplicity) which just uses a standard array variable rather than a query and that one is working fine, so I guess it must something to do with the custom post type query.
You'll see in the code that I've tried get_posts (commented) as well as WP_Query but they both present the same issue.
Where am I going wrong here?
I created a custom post type "stm_media_gallery"
And three category inside this custom post type.
I want to display category name associated with each post.
<?php $gallery_query = new WP_Query( array('post_type' =>
'stm_media_gallery', 'posts_per_page' => -1) );
if( $gallery_query->have_posts() ) :
while( $gallery_query->have_posts() ) : $gallery_query->the_post(); ?>
--Display post name and its category name
<?php endif; ?>
<?php endwhile; ?>
You just need to put following code inside loop :
<div>
<?php
foreach((get_the_category()) as $category){
echo $category->name."<br>";
echo category_description($category);
}
?>
</div>
Update in existing code
<?php $gallery_query = new WP_Query(
array('post_type' => 'stm_media_gallery',
'posts_per_page' => -1) );
if( $gallery_query->have_posts() ) :
while( $gallery_query->have_posts() ) : $gallery_query->the_post();
$gallery_category = get_the_category( get_the_ID() );
the_title( '<h3>', '</h3>' );
echo "<br>";
<?php foreach ( $gallery_category as $key => $value) { echo $value->category_nicename; } ?>
<?php endif; ?>
<?php endwhile; ?>
You can use the pre-made WordPress function the_category( $separator, $parents, $post_id ) to print the post categories as links.
Further information on the WordPress Codex: Function Reference: the_category
Edit: Print only the names:
$categories = get_the_category();
if ( ! empty( $categories ) ) {
echo esc_html( $categories->name );
}
Put this inside While Loop
global $post;
$postcat = get_the_category( $post->ID );
I'm adding a custom field to page that would select a blog category to feature on that page. All the other fields are working fine, so, i'll post code related only to this field. Getting error 500 when loading page editor.
$feat_blog = isset( $values['feat_blog'] ) ? esc_attr( $values['feat_blog'][0] ) : "";
This is the field itself
<select name="feat_blog" id="feat_blog" value="<?php echo $feat_blog; ?>">
<?php $categories = get_categories(); foreach($categories as $category) { ?>
<option value="<?php echo $category->slug ?>"> <?php echo $category->name ?></option>
<?php } ?>
</select>
And sanitization code that's actually causing trouble
if ( isset( $_POST['feat_blog'] )){
$valid_values = array(
categories = get_categories();
foreach($categories as $category) {
echo $category->slug,
}
);
$value = sanitize_text_field( $_POST['feat_blog'] );
if( in_array( $value, $valid_values ) ) {
update_post_meta( $post->ID, 'feat_blog', $value );
}
}
There are quite a few things wrong with your code here...
You are putting ; in an array and attempting to assign a variable there.
You are echoing in an array.
You are running functions inside an array.
You are missing the $ infront of the $categories variable.
if ( isset( $_POST['feat_blog'] )) {
$categories = get_categories();
$valid_values = array();
foreach($categories as $category) {
$valid_values[] = $category->slug;
}
$value = sanitize_text_field( $_POST['feat_blog'] );
if( in_array( $value, $valid_values ) ) {
update_post_meta( $post->ID, 'feat_blog', $value );
}
}
What I did here is I moved the $categories variable declaration outside of the foreach loop and set the $valid_values array BEFORE the loop. If you set it inside the loop it is going to reset every time the loop occurs. You also can't use ; inside of an array as that is intended to close the statement.
I have already created custom meta box at my custom post type.
so I create drop down list to choose a Teacher's name and the Class.
The value can be shown in the dropdown, but after publishing the post the value cannot save and dropdown set to default again.
can somebody know, if I am missing part or wrong code here?
Thanks if you wanna help, so here's my code:
function portfolio_student(){
add_meta_box( 'portfolio_student', 'Select The Teachers and Classes', 'meta_box_data', 'portfolio', 'normal', 'high' ); }
function meta_box_data(){
// $post is already set, and contains an object: the WordPress post
global $post;
$values = get_post_custom( $post->ID );
$teachers = isset( $values['the_teachers'] ) ? esc_attr( $values['the_teachers'] ) : '';
$classes = isset( $values['the_classes'] ) ? esc_attr( $values['the_classes'] ) : '';
// We'll use this nonce field later on when saving.
wp_nonce_field( 'my_meta_box_nonce', 'meta_box_data' );
?>
<p>
<label for="the_teachers">Teacher</label>
<select name="the_teachers" id="the_teachers">
<option value="0">-- Select Class --</option>
<?php
$args = array(
'numberposts' => -1,
'post_type' => 'teacher'
);
$teacher_posts = get_posts($args);
foreach( $teacher_posts as $post ) : setup_postdata($post); ?>
<option value="<?php echo $post->ID; ?>" <?php selected($teachers, $post->ID); ?>><?php the_title(); ?></option>
<?php endforeach; ?>
</select>
</p>
<p>
<label for="the_classes">Class</label>
<select name="the_classes" id="the_classes">
<option value="0">-- Select Class --</option>
<?php
$args = array(
'numberposts' => -1,
'post_type' => 'class'
);
$class_posts = get_posts($args);
foreach( $class_posts as $post ) : setup_postdata($post); ?>
<option value="<?php echo $post->ID; ?>" <?php selected($classes, $post->ID); ?>><?php the_title(); ?></option>
<?php endforeach; ?>
</select>
</p>
<?php}
add_action( 'save_post', 'cd_meta_box_save' );function cd_meta_box_save( $post_id ){
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
// if our nonce isn't there, or we can't verify it, bail
if( !isset( $_POST['meta_box_data'] ) || !wp_verify_nonce( $_POST['meta_box_data'], 'my_meta_box_nonce' ) )
return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) )
return;
// Make sure your data is set before trying to save it
if( isset( $_POST['the_teachers'] ) )
//Update Meta Data
$teacher_meta = $_POST['the_teachers'];
//EndUpdate
update_post_meta( $post_id, 'the_teachers', $teacher_meta );
if( isset( $_POST['the_classes'] ) )
//Update Meta Data
$class_meta = $_POST['the_classes'];
//EndUpdate
update_post_meta( $post_id, 'the_classes', $class_meta ); }
Try changing these
update_post_meta( $post_id, 'the_teachers', $teacher_meta );
update_post_meta( $post_id, 'the_classes', $class_meta );
To
update_post_meta( $post->ID, 'the_teachers', $teacher_meta );
update_post_meta( $post->ID, 'the_classes', $class_meta );
Since you have declared $post as the global variable
Ask to everyone, i have problem. Here i try to use multiple chechbox to my custom post metabox.
<?php
function prodetail() {
add_meta_box('pro_metabox', 'Detail Property', 'pro_metabox', 'property', 'normal', 'default');
}
function pro_metabox() {
global $post;
echo '<input type="hidden" name="eventmeta_noncename" id="eventmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
$postmeta = maybe_unserialize( get_post_meta( $post->ID, 'elements', true ) );
$elements = array(
'pool' => 'Pool',
'garage' => 'Garage',
'balcon' => 'Balcon',
'yard' => 'Yard',
'internet' => 'Internet'
);
foreach ( $elements as $id => $element) {
if ( is_array( $postmeta ) && in_array( $id, $postmeta ) ) {
$checked = 'checked="checked"';
} else {
$checked = null;
}
?>
<div class="pro-inn">
<div class="procols">
<div class="pro-inn">
<input type="checkbox" name="multval[]" value="<?php echo $id; ?>" <?php echo $checked; ?> />
<?php echo $element;?>
</div>
</div>
</div>
<?php
}
}
function pro_meta($post_id, $post) {
if ( !wp_verify_nonce( $_POST['eventmeta_noncename'], plugin_basename(__FILE__) )) {
return $post->ID;
}
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;
if ( ! empty( $_POST['multval'] ) ) {
update_post_meta( $post_id, 'elements', $_POST['multval'] );
} else {
delete_post_meta( $post_id, 'elements' );
}
}
add_action('save_post', 'pro_meta', 1, 2);
?>
help me to add code to show this checked result to single.php because my code use foreach just show Array text not show text like Pool Garage Balcon ect.
Thanks
Use this code in your single.php file for your custom post
$meta_value = get_post_meta( $post->ID, 'elements', true );
foreach($meta_value as $key=>$value){
echo $value . ' ';
}
It will show results same as you mentioned in the question ie:
(Pool Garage Balcon ect.)