Wordpress Metabox - problem with display value in page template - wordpress

I am adding a custom metabox for WordPress, I am able to save the value but unable to display the value in a page template.
Code in function.php
//Custome MetaBox
function custom_metabox() {
add_meta_box("custom_metabox_01", "Custom Metabox", "custom_metabox_field", "page", "side", "default", null);
}
add_action("admin_init", "custom_metabox");
function custom_metabox_field() {
wp_nonce_field(basename(__FILE__), "custom_metabox_01_nonce");
global $post;
$data = get_post_custom($post->ID);
$val = isset($data['custom_input']) ? esc_attr($data['custom_input'][0]) : 'no value';
echo '<input type="text" name="custom_input" id="custom_input" value="'.$val.'" />';
}
function save_detail() {
global $post;
if (!isset($_POST["custom_metabox_01_nonce"]) || !wp_verify_nonce($_POST["custom_metabox_01_nonce"], basename(__FILE__))){
return $post->ID;
}
if(!current_user_can("edit_post", $post->ID)){
return $post->ID;
}
if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE) {
return $post->ID;
}
update_post_meta($post->ID, "custom_input", $_POST["custom_input"]);
}
add_action("save_post", "save_detail");
Code in template-parts/content/content-page.php
<div class="metabox">
<?php
$custom_post_type = get_post_meta($post->ID, 'custom_input', true);
echo 'meta box value: ' . $custom_post_type;
?>
</div>
Also please suggest to me how to implement the same only for "theme-template/default.php( Custom Page Template)"
Thanks in advance.

Related

Why is the filter the_title not working when the_content is working fine?

Function and filter to display a player post titles:
function wpb_after_post_content($content){
if (is_single()) {
$id=get_the_ID();
$post_meta=get_post_meta(get_the_ID(), 'enclosure', TRUE);
$mp3=explode('.mp3',$post_meta);
$title=get_the_title();
if(count($mp3)>1)
{
$player = '<div class="post_player">' . do_shortcode('[fap_track url="'.trim($mp3[0]).'.mp3" title=url="'.$title.'" share="" cover="" meta="" layout="list" enqueue=no auto_enqueue=yes]')."</div>";
$content=$player.$content;
}
}
if (is_single()) {
$id=get_the_ID();
$post_meta=get_post_meta(get_the_ID(), 'enclosure', TRUE);
$mp3=explode('.mp3',$post_meta);
$title=get_the_title();
if(count($mp3)>1)
{
$player = '<div class="zoomsounds_player">'. do_shortcode('[zoomsounds_player source="'.trim($mp3[0]).'.mp3" play_in_footer_player="on" config="default" artistname="'.get_post_meta($id, 'arxiu_de_so', true).'" config="" ]');
/**if (wp_is_mobile())*/ {
if(get_post_meta($id, 'arxiu_de_so', true)!=""){
/** $player .= " <p id='arxiu_so'> Arxiu de so: ".get_post_meta($id, 'arxiu_de_so', true)."</p>";*/
/**$player .= '<span id="arxiuVal" style="opacity:1"> '.get_post_meta($id, 'arxiu_de_so', true).'</span>';*/
}
}
$player .="</div>";
$content=$player.$content;
}
}
return $content;
}
add_filter( "the_content", "wpb_after_post_content" );
The above code works fine with the_content filter and displays the player below the featured image. However, when I use this function with the the_title filter, the page doesn't load at all. The reason I want to use the_title is because I want the player to display above the featured image but below the post title.
Screenshot:-
This screenshot is to show that with the_content the player displays however it displays below post image.
Please have a look as below:
If you want to use the_title(), then you no need to pass the post_id in the the_title(), we have some params for the_title() if you want to add them like as below:
$before
(string) (Optional) Markup to prepend to the title.
Default value: ''
$after
(string) (Optional) Markup to append to the title.
Default value: ''
$echo
(bool) (Optional) Whether to echo or return the title. Default true for the echo.
Default value: true
If you want to use get_the_title(), then you must need to pass post_id inside the get_the_title($postId);
According to your code snippet, you must update your code with as below for get_the_title():
<?php
function wpb_after_post_content($content){
if (is_single()) {
$id=get_the_ID();
$post_meta=get_post_meta(get_the_ID(), 'enclosure', TRUE);
$mp3=explode('.mp3',$post_meta);
$title=get_the_title($id);
if(count($mp3)>1) {
$player = '<div class="post_player">' . do_shortcode('[fap_track url="'.trim($mp3[0]).'.mp3" title=url="'.$title.'" share="" cover="" meta="" layout="list" enqueue=no auto_enqueue=yes]')."</div>";
$content=$player.$content;
}
}
return $content;
}
add_filter( "the_content", "wpb_after_post_content" );
?>
And for the the_title(), you should update your code with as below:
<?php
function wpb_after_post_content($content){
if (is_single()) {
$id=get_the_ID();
$post_meta=get_post_meta(get_the_ID(), 'enclosure', TRUE);
$mp3=explode('.mp3',$post_meta);
$title=get_the_title();
if(count($mp3)>1)
{
$player = '<div class="post_player">' . do_shortcode('[fap_track url="'.trim($mp3[0]).'.mp3" title=url="'.the_title().'" share="" cover="" meta="" layout="list" enqueue=no auto_enqueue=yes]')."</div>";
$content=$player.$content;
}
}
return $content;
}
add_filter( "the_content", "wpb_after_post_content" );
?>
NOTE: You have not declared the title parameter in the zoomsounds_player shortcode so please pass and update accordingly.
I hope it would help you out.

Check custom meta checkbox if it's checked Wordpress

// Checkbox Meta
add_action("admin_init", "checkbox_init");
function checkbox_init(){
add_meta_box("checkbox", "Checkbox", "checkbox", "post", "normal", "high");
}
function checkbox(){
global $post;
$custom = get_post_custom($post->ID);
$field_id = $custom["field_id"][0];
?>
<label>Check for yes</label>
<?php $field_id_value = get_post_meta($post->ID, 'field_id', true);
if($field_id_value == "yes") $field_id_checked = 'checked="checked"'; ?>
<input type="checkbox" name="field_id" value="yes" <?php echo $field_id_checked; ?> />
<?php
}
// Save Meta Details
add_action('save_post', 'save_details');
function save_details(){
global $post;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $post->ID;
}
update_post_meta($post->ID, "field_id", $_POST["field_id"]);
}
I needed to add a custom meta checkbox on the posts page to enable certain content. The code above is from another stackoverflow answer. When I hit update post, it does save the check value, but I don't understand how to test if it's checked on a page I want to display the content.
doing if (isset()) tests if there is a value, so it's always returning true even if it's not checked. Is there a way I can test for the checked="checked" value? That is what is updating if I inspect element.
Check for on
if($field_id_value == "on") $field_id_checked = 'checked="checked"';

Wordpress unique checkbox

I have created a custom field "headline" in posts that is handled by a checkbox. Now I want that when the post is saved and the checkbox is checked, all "headline" checkboxes are emptied in the other posts. If this works correctly there should only be one other post with that checkbox checked.
function createHeadlineField()
{
$post_id = get_the_ID();
if (get_post_type($post_id) != 'post') {
return;
}
$value = get_post_meta($post_id, '_headline_field', true);
wp_nonce_field('headline_nonce_'.$post_id, 'headline_nonce');
?>
<div class="misc-pub-section misc-pub-section-last">
<label><input type="checkbox" value="1" <?php checked($value, true, true); ?> name="_headline_field" /><?php _e('This post is the top Story', 'pmg'); ?></label>
</div>
<?php
}
function saveHeadlineField($post_id)
{
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
if (
!isset($_POST['headline_nonce']) ||
!wp_verify_nonce($_POST['headline_nonce'], 'headline_nonce_'.$post_id)
) {
return;
}
if (!current_user_can('edit_post', $post_id)) {
return;
}
if (isset($_POST['_headline_field'])) {
update_post_meta($post_id, '_headline_field', $_POST['_headline_field']);
} else {
delete_post_meta($post_id, '_headline_field');
}
}
Has anybody a clue how to do that? I guess I have to query the posts for posts with _headline_field values and delete these before updating the actual post.
thx
so if u want to query the posts with the metakey Headline u can do something like that:
$posts = array();
$query = new WP_Query(array('meta_key' => Headline, 'meta_value'=>YOURVALUE, 'posts_per_page' => LIMIT (-1 for endless)))
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$posts[] = $query->post;
}
wp_reset_postdata();
}
return $posts;
I tried to do it like that:
if (isset($_POST['_headline_field'])) {
//query posts with custom field selected
$args = array ( 'meta_key' => '_headline_field', 'meta_value' => '1', LIMIT -1 );
$headline_query = new WP_Query( $args );
if ( have_posts() ):
while ( have_posts() ) :
$headline_query->the_post();
$headline_query->delete_post_meta(get_the_ID(), '_headline_field');
endwhile;
endif;
update_post_meta($post_id, '_headline_field', $_POST['_headline_field']);
Ok, found a solution.
I just used the "delete_post_meta_by_key()" function to erase alle post meta with the key _headline_field before writing the new value into the DB.
if (isset($_POST['_headline_field'])) {
delete_post_meta_by_key( '_headline_field' );
update_post_meta($post_id, '_headline_field', $_POST['_headline_field']);
}

Multi select meta box

I have added multi select meta box to custom post-type it appears good but save only one selection . How to change the code below to save all selected options.
add_action( 'add_meta_boxes', 'add_condition_metaboxes'); function add_scondition_metaboxes() {
add_meta_box('condition', 'Информация спикеров', 'wpt_condition_author', 'condition', 'side', 'default');} function wpt_scondition_author() {
global $post;
// Noncename needed to verify where the data originated
echo '<input type="hidden" name="conditionmeta_noncename" id="conditionmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
// Get the author data if its already been entered
$my_dropdown = get_post_meta($post->ID, '_dappcf_i_dropdown', true);
// Echo out the field
$posts = get_posts(array('post_type'=> 'speakers', 'post_status'=> 'publish', 'suppress_filters' => false, 'posts_per_page'=>-1));
//here you add the HTML of the dropdown you add something like
echo '<p>Select the speaker: <select multiple="yes" name="_dappcf_i_dropdown" class="widefat" style="width:170px">';
foreach ($posts as $post) {
echo '<option value="', $post->ID, '">'.$post->post_title.'</option>'; }
echo '</select>'; } function wpt_save_condition_meta($post_id, $post) {
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if ( !wp_verify_nonce( $_POST['conditionmeta_noncename'], plugin_basename(__FILE__) )) {
return $post->ID;
}
// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;
// OK, we're authenticated: we need to find and save the data
// We'll put it into an array to make it easier to loop though.
$condition_meta['_dappcf_i_dropdown'] = $_POST['_dappcf_i_dropdown'];
// Add values of $testimonial_meta as custom fields
foreach ($condition_meta as $key => $value) { // Cycle through the $testimonial_meta array!
if( $post->post_type == 'revision' ) return; // Don't store custom data twice
$value = implode(',', (array)$value); // If $value is an array, make it a CSV (unlikely)
if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value
update_post_meta($post->ID, $key, $value);
} else { // If the custom field doesn't have a value
add_post_meta($post->ID, $key, $value);
}
if(!$value) delete_post_meta($post->ID, $key); // Delete if blank
} } add_action('save_post', 'wpt_save_condition_meta', 1, 2); // save the custom fields
The options are queried from other custom post-type and the number of post can be changed.

Wordpress - Meta Field Update

I created a couple meta fields in Wordpress for a Custom Post Type. They are 'Price' and 'Details'. If I got to the 'edit post' page, and i change something in one of these fields, but then decide to just leave the page by hitting 'back' in the browser or closing the window, i get a warning from my browser "are you sure you want to leave the page?". When I hit 'Yes', it erases anything that's in those 2 fields, even what was previously stored before my editing.
Any idea why this could be?
Here's some of my code in functions.php:
add_action("admin_init", "admin_init");
function admin_init()
{
add_meta_box("price", "Price", "price_field", "product", "normal", "high");
add_meta_box("details", "Details", "details_field", "product", "normal", "high");
}
function price_field()
{
global $post;
$custom = get_post_custom($post->ID);
$price = $custom["price"][0];
?>
<label>Price: $</label>
<input name="price" value="<?php echo $price; ?>" />
<?php
}
function details_field()
{
global $post;
$custom = get_post_custom($post->ID);
$details = $custom["details"][0];
?>
<label>Details:</label>
<input name="details" rows='5' value="<?php echo $details; ?>" />
<?php
}
/*--------------------------------*/
/* Save PRICE and DETAILS fields */
/*--------------------------------*/
add_action('save_post', 'save_details');
function save_details()
{
global $post;
update_post_meta($post->ID, "price", $_POST["price"]);
update_post_meta($post->ID, "details", $_POST["details"]);
}
This is because you didnt add filtering in your save details method. Remember action hook "save_post" is also called once the post is auto save in draft even if you didnt click the update or the publish button. Try this
add_action('save_post', 'save_details');
function save_details($post_id){
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
// uncomment if youre using nonce
//if ( !wp_verify_nonce( $_POST['my_noncename'], plugin_basename( __FILE__ ) ) )
// return;
// Check permissions
//change the "post" with your custom post type
if ( 'post' == $_POST['post_type'] )
{
if ( !current_user_can( 'edit_page', $post_id ) )
return;
}
else
{
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
//if success go to your process
//you can erase your global $post and dont use $post->ID rather change it with $post_id since its our parameter
update_post_meta($post_id, "price", $_POST["price"]);
update_post_meta($post_id, "details", $_POST["details"]);
}
NOTE: in if ( 'post' == $_POST['post_type'] ) line, change "post" to your post type

Resources