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']);
}
Related
I am writing a 404.php for wordpress. I have the plugin 'rolescoper' installed, and some pages require the user be logged in to view. Rolescoper doesn't offer any way to distinguish between a page not found (404) and a permission denied (403).
I've been able to build this functionality into my pages using the following code:
$the_query = new WP_Query ( 'pagename=' . $_SERVER['REQUEST_URI'] );
$is_valid_page = ! empty ( $the_query -> queried_object -> post_title );
But, surprisingly, the same method does does not work for posts:
$args = array (
'post_type' => 'post',
'name' => str_replace ( "/", "", $_SERVER['REQUEST_URI'] )
);
$the_post_query = new WP_Query ( $args );
$is_valid_post = ! empty ( $the_post_query -> queried_object -> post_title );
When I do a var_dump on $the_post_query i get something that shows 0 results found. I am sure that the page I'm checking for exists.
Any idea how to use wp_query() to query for a post by slug?
Thanks!
After digging through the docs, I found that Rolescoper provided a nice function, is_restricted_rs(), for solving this problem:
//get the slug requested
$slug = $_SERVER [ 'REQUEST_URI' ];
//First check if it's a page and restricted
$page_id = get_page_by_path ( $slug )->ID;
$page_restricted = is_restricted_rs ( $page_id );
//Then check if it's a post and restricted
$args = array(
'name' => $slug,
'post_type' => 'post',
'post_status' => 'publish',
'numberposts' => 1
);
$my_posts = get_posts($args);
if ( $my_posts ) {
$post_id = $my_posts[0]->ID;
}
$post_restricted = is_restricted_rs ( $post_id );
//then set $content_restricted for use below
$content_restricted = $post_restricted || $page_restricted;
The rolescoper plugin has become defunct and we developed a solution which does not require any external plugin. Instead, we added some code to our theme and added a custom field to each page that we wanted to restrict access to.
This isn't as robust as rolescoper was, but for our use case it was perfect. We have only a few user classes and so I just hardcode the different classes and that's enough for us. I'm sure a similar solution could be used for more complex cases, especially if you expanded on the custom UI code.
I happened to name the field "dhamma_perms" but you could name it anything you want:
function is_restricted() {
return item_restricted(get_post(), wp_get_current_user());
}
function item_restricted($page, $user) {
$dhamma_perms = get_post_meta($page->ID, "dhamma_perms", true);
$requires_os = $dhamma_perms == "oldstudents";
$requires_worker = $dhamma_perms == "workers";
if (!is_user_logged_in()) {
return $requires_os || $requires_worker;
} else if (get_userdata($user->ID)->user_login == "oldstudent") {
return $requires_worker;
} else {
//dhammaworkers and all named users have full read access
return false;
}
}
I then modified any page which could be restricted to have code like this at the top:
<?php get_header(); ?>
<?php if (is_restricted()) : ?>
<?php show_404(); ?> //I just pasted the full content of our 404 page into a function. The 404 page shows a faux-403 page (WP doesn't have real 403 pages) if the content exists but is restricted.
<?php else: ?>
//show normal page stuff
I also modified the header.php to have a proper title for 404 and 403 pages:
<?php if (is_restricted()) : ?>
<title> <?php echo "Login Required " . get_theme_mod('dhamma_title_separator') . " " . get_bloginfo('name'); ?></title>
<?php else: ?>
<title><?php wp_title( get_theme_mod('dhamma_title_separator'), true, "right" ); bloginfo('name'); ?></title>
<? endif; ?>
Finally, I added a custom UI to posts and pages so it's easy to select permissions:
//Register the permissions metabox for posts and pages
function add_perms_box( $post ) {
$screens = [ 'post', 'page', 'wporg_cpt' ];
foreach ( $screens as $screen ) {
add_meta_box(
'dhamma_perms_box', // Unique ID
'Permissions', // Box title
'perms_box_html', // Content callback, must be of type callable
$screens // Post type
);
}
}
function perms_box_html() {
$value = get_post_meta(get_the_ID(), "dhamma_perms", true);
?>
<select name="dhamma_perms" id="dhamma_perms" class="postbox">
<option value="public" <?php selected($value, 'public');?>>Public</option>
<option value="oldstudents" <?php selected($value, 'oldstudents');?>>Old Students Only</option>
<option value="workers" <?php selected($value, 'workers');?>>Dhamma Workers Only</option>
</select>
<?php
}
add_action('add_meta_boxes', 'add_perms_box');
function dhamma_meta_save( $post_id ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
// Exits script depending on save status
if ( $is_autosave || $is_revision ) {
return;
}
// Checks for input and sanitizes/saves if needed
if( isset( $_POST[ 'dhamma_perms' ] ) ) {
update_post_meta( $post_id, 'dhamma_perms', $_POST[ 'dhamma_perms' ] );
}
}
add_action( 'save_post', 'dhamma_meta_save' );
This created a new dropdown on each page and post for us:
I hope this is helpful for anyone else trying to get some simple permissions on a wordpress site!
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.
i'm add code in functions create more field in category as:
add_action ( 'edit_category_form_fields', 'extra_category_fields');
//add extra fields to category edit form callback function
function extra_category_fields( $tag ) { //check for existing featured ID
$t_id = $tag->term_id;
$cat_meta = get_option( "category_$t_id");
?>
<label for="extra3"><?php _e('Add Noi dung 3'); ?></label>
<?php $settings = array( 'textarea_name' => 'css[extra3]' ); wp_editor( $cat_meta['extra3'], 'css-extra3',$settings ); ?>
<?php
add_action ( 'edited_category', 'save_extra_category_fileds');
// save extra category extra fields callback function
function save_extra_category_fileds( $term_id ) {
if ( isset( $_POST['css'] ) ) {
$t_id = $term_id;
$cat_meta = get_option( "category_$t_id");
$cat_keys = array_keys($_POST['css']);
foreach ($cat_keys as $key){
if (isset($_POST['css'][$key])){
$cat_meta[$key] = $_POST['css'][$key];
}
}
//save the option array
update_option( "category_$t_id", $cat_meta );
}
}
}
and add code in index print wp_editor:
$cat_id = Category_ID; $cat_data = get_option("category_$cat_id"); echo do_shortcode($cat_data['extra3']);
when i'm add text to textarea with wp_editor is ok; but i'm add media or shortcode in page view echo code as : <a href=\"url\" or width=\"300\" or height=\"225\" ....
Any code as ="value" when i'm save => =\"value\". if i've save 5 have code =\\\\\"value\\\\\"
this is picture code when i'm add media
And when i'm save wp_editer:
How to fix it's.
Thanks
<?php $settings = array( 'textarea_name' => 'css[extra3]' ); wp_editor( $cat_meta['extra3'], 'css-extra3',$settings ); ?>
remove ^ php close tag
This will not execute the next statements because this ?> will close the php tag
I'm going to break my brain..
I've created a new metabox for my custom post type "book".
I'm using a lot of different type of fields like input text, checkbox, select, textarea, taxonomy select and repeatable and everything work great!
But now I'd like to do a more difficult step..
Is it possible to do a repeatable field with 2 fields inside it?
I would like have a select and an input text near it.. inside the select admin can choose the shop (es. Ibs or Amazon) and in the input field he can write the url for sell the book.
This is my code:
/* META Book */
function add_mycustom_meta_box() {
add_meta_box(
'custom_meta_box',
'Info book',
'show_custom_meta_box', // $callback
'product',
'normal',
'high');
}
// Field Array
$prefix = 'custom_';
$custom_meta_fields = array(
array(
'label' => 'Link vendita',
'desc' => 'Inserisci l url dei siti esterni',
'id' => $prefix.'repeatable',
'type' => 'repeatable',
'options' => array(
'amazon' => array(
'label' => 'Amazon',
'value' => 'amazon'
),
'ibs' => array(
'label' => 'Ibs',
'value' => 'ibs'
)
)
)
);
// Callback
function show_custom_meta_box() {
global $custom_meta_fields, $post;
// Use nonce for verification
echo '<input type="hidden" name="custom_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';
// Build metabox
echo '<table class="form-table">';
foreach ($custom_meta_fields as $field) {
// get value of this field if it exists for this post
$meta = get_post_meta($post->ID, $field['id'], true);
// begin a table row with
echo '<tr>
<th><label for="'.$field['id'].'">'.$field['label'].'</label></th>
<td>';
switch($field['type']) {
// if repeatable
case 'repeatable':
echo '<a class="repeatable-add button" href="#">+</a>
<ul id="'.$field['id'].'-repeatable" class="custom_repeatable">';
$i = 0;
if ($meta) {
foreach($meta as $row) {
echo '<li><span class="sort hndle">|||</span>';
// Select ibis or amazon
echo '<select name="'.$field['id'].'" id="'.$field['id'].'">';
foreach ($field['options'] as $option) {
echo '<option', $row == $option['value'] ? ' selected="selected"' : '', ' value="'.$option['value'].'">'.$option['label'].'</option>';
}
echo '</select>';
// end select
echo '<input type="text" name="'.$field['id'].'['.$i.']" id="'.$field['id'].'" value="'.$row.'" size="30" data-shop="'.$option.'" />
<a class="repeatable-remove button" href="#">-</a></li>';
$i++;
}
} else {
echo '<li><span class="sort hndle">|||</span>';
// Select ibis o amazon
echo '<select name="'.$field['id'].'" id="'.$field['id'].'">';
foreach ($field['options'] as $option) {
echo '<option', $row == $option['value'] ? ' selected="selected"' : '', ' value="'.$option['value'].'">'.$option['label'].'</option>';
}
echo '</select>';
// Fine select
echo '<input type="text" name="'.$field['id'].'['.$i.']" id="'.$field['id'].'" value="" size="30" />
<a class="repeatable-remove button" href="#">-</a></li>';
}
echo '</ul>
<span class="description">'.$field['desc'].'</span>';
break;
} //end switch
echo '</td></tr>';
} // end foreach
echo '</table>';
}
// Save the Data
function save_custom_meta($post_id) {
global $custom_meta_fields;
// verify nonce
if (!wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__)))
return $post_id;
// check autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return $post_id;
// check permissions
if ('page' == $_POST['post_type']) {
if (!current_user_can('edit_page', $post_id))
return $post_id;
} elseif (!current_user_can('edit_post', $post_id)) {
return $post_id;
}
// loop through fields and save the data
foreach ($custom_meta_fields as $field) {
$old = get_post_meta($post_id, $field['id'], true);
$new = $_POST[$field['id']];
if ($new && $new != $old) {
update_post_meta($post_id, $field['id'], $new);
} elseif ('' == $new && $old) {
delete_post_meta($post_id, $field['id'], $old);
}
} // end foreach
}
add_action('save_post', 'save_custom_meta');
The repeatable field generate an array and it is ok, but what I can do to store the select value also?
Hope someone can help me
Thanks
I'm sure you can put in dynamic fields into custom Metaboxes inside the edit screen of any post type.
I build this for the Language Field Plugin into the admin page on http://wordpress.org/plugins/language-field/
I was relying on this example
http://www.mustbebuilt.co.uk/2012/07/27/adding-form-fields-dynamically-with-jquery/
Generally take these steps
Add custom Meta box with this example
http://codex.wordpress.org/Function_Reference/add_meta_box#Examples
when it comes to these lines
$mydata = sanitize_text_field( $_POST['myplugin_new_field'] );
// Update the meta field in the database.
update_post_meta( $post_id, '_my_meta_value_key', $mydata );
loop thru the fields created with example above.
Question for you regarding wordpress.
I want to display a notification at the top of post.php?action=edit if the get_post_meta is a certain value... any advice how I can more effectively accomplish this? I seem to be getting no response from this code.
add_action('admin_notices', 'HMMultipostMU_notifyChild' );
if( !function_exists( 'HMMultipostMU_notifyChild' ) ){
function HMMultipostMU_notifyChild(){
global $hmMultipostMU;
if( !isset( $hmMultipostMU ) ){
return;
}
if($meta = get_post_meta($post_id, 'HMMultipostMU_parent', true)) {
$parent = unserialize( $meta );
if(!empty($parent)) {
foreach ($parent as $key => $value) {
switch_to_blog( $key );
echo '<div id="message" class="updated highlight"> WARNING: This is a child article! Please <a href='. get_edit_post_link( $value ). '>click here</a> to edit this article as the Parent. Be Aware, this may switch blog sites.<br /> </div>';
}
restore_current_blog();
}
}
}
}
I found my issue! ahhh. $post_id wasn't defined until the page runs... I had to change it to $_GET var. Gr sorry thanks!