Show custom-field selection - Wordpress - php

I added a content rating system to my platform where the authors can select which audience their post is appropriate for. Currently, these options are available:
Unrated
G
PG
R
The code that I use to display the rating options on the post edit page is:
// Article Content Rating
add_action( 'add_meta_boxes', 'rating_select_box' );
function rating_select_box() {
add_meta_box(
'rating_select_box', // id, used as the html id att
__( 'Content Rating (optional)' ), // meta box title
'rating_select_cb', // callback function, spits out the content
'post', // post type or page. This adds to posts only
'side', // context, where on the screen
'low' // priority, where should this go in the context
);
}
function rating_select_cb( $post ) {
global $wpdb;
$value = get_post_meta($post->ID, 'rating', true);
echo '<div class="misc-pub-section misc-pub-section-last"><span id="timestamp"><label>Article Content Rating: </label>';
$ratings = array(
1 => ' G ',
2 => ' PG ',
3 => ' R ',
);
echo '<select name="rating">';
echo '<option value=""' . ((($value == '') || !isset($ratings[$value])) ? ' selected="selected"' : '') . '> Unrated </option>';
// output each rating as an option
foreach ($ratings as $id => $text) {
echo '<option value="' . $id . '"' . (($value == $id) ? ' selected="selected"' : '') . '">' . $text. '</option>';
}
echo '</select>';
echo '</span></div>';
}
add_action( 'save_post', 'save_metadata');
function save_metadata($postid)
{
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return false;
if ( !current_user_can( 'edit_page', $postid ) ) return false;
if( empty($postid) ) return false;
if ( is_null($_REQUEST["rating"]) ) {
delete_post_meta($postid, 'rating');
} else {
update_post_meta($postid, 'rating', $_REQUEST['rating']);
}
}
// END Article Content Rating
Now, the problem is, what code do I add to single.php to display their choice? So for instance, if the author selected PG, then I want to echo 'Content Rating: PG'; or if it was on default (unrated), I want to echo 'Content Rating: Unrated';. How is this possible? Ideally, a solution that is light on the server as my platform is heavily trafficked.

You already use the delete_post_meta() and update_post_meta() functions to remove and modify the custom values. Simply use the get_post_meta() function to obtain the value for the current post, and echo it out as you see fit.
If you're in The Loop, it would be something like:
$rating = get_post_meta(get_the_ID(), 'rating', TRUE);
Edit:
You already know your ID to rating mapping (I might make this mapping a global array, or some defines, or something similar). Simply use that to look up the string to output:
$ratings = array(
1 => 'G',
2 => 'PG',
3 => 'R'
);
if(array_key_exists($rating, $ratings)) {
echo "Content Rating: $ratings[$rating]";
} else {
echo "Content Rating: Unrated";
}

It looks as if you're saving the key to your custom field rather than its value. I suppose this would be alright if you planned on redeclaring your $ratings array, or (God forbid) use it globally. But still, it would probably be best if you saved the actual Rating rather than its ID number.
So change this line:
foreach ($ratings as $id => $text) {
echo '<option value="' . $id . '"' . (($value == $id) ? ' selected="selected"' : '') . '">' . $text. '</option>';
}
To this:
echo '<option value="Unrated"' . ((!$value || $value == 'Unrated' ? ' selected="selected"' : '') . '">Unrated</option>';
foreach ($ratings as $id => $text) {
echo '<option value="' .trim($text). '"' . (($value == trim($text)) ? ' selected="selected"' : '') . '">' . $text. '</option>';
}
After setting your value within the post, you can add this in single.php:
if(have_posts()) : while(have_posts()) : the_post();
echo 'Content Rating: '.get_post_meta($post->ID, 'rating', true);
endwhile;endif;
UPDATE:
As mentioned in my comments, I personally try to avoid globals and redeclaring things as much as possible. So if you would prefer to still reference your ratings by Key, you can get around globals and redeclaring your ratings array by adding a few simple functions:
functions.php
function gw_get_ratings_array()
{
$ratings = array(
1 => 'G',
2 => 'PG',
3 => 'R'
);
return $ratings;
}
function gw_get_rating($key=0)
{
$i = (int)$key;
$ratings = gw_get_ratings_array();
return isset($ratings[$i]) && $ratings[$i] ? $ratings[$i] : 'Unrated';
}
single.php
if(have_posts()) : while(have_posts()) : the_post();
$rating_id = get_post_meta($post->ID, 'rating', true);
echo 'Content Rating: '.gw_get_rating($rating_id);
endwhile;endif;
This way, if you ever need to add more Rating Types, you only need to alter the gw_get_ratings_array function rather than searching for each declaration of the array itself.

Related

Wordpress shortcode shows as plain text in one view, works in other

I have this complex loop:
<?php
$args = array(
'cat' => 54,
'order' => 'ASC',
'posts_per_page' => -1
);
$query = new WP_Query($args);
$q = array();
while ( $query->have_posts() ) {
$query->the_post();
$a = '<h2>' . get_the_title() .'</h2>'
. get_the_post_thumbnail() .
'<p>' . get_the_content("...plačiau") . '</p>';
$categories = get_the_category();
foreach ( $categories as $key=>$category ) {
$b = '<h1 class="thetitle">' . $category->name . '<span>Išskleisti <i class="fa fa-arrow-circle-down"></i></span></h1>';
}
$q[$b][] = $a; // Create an array with the category names and post titles
}
/* Restore original Post Data */
wp_reset_postdata();
foreach ($q as $key=>$values) {
echo $key;
echo '<div class="straipsniai">';
foreach ($values as $value){
if (count($values) == 1) {
echo '<div class="vienas">' . $value . '</div>';
} else if (count($values) == 2) {
echo '<div class="du">' . $value . '</div>';
} else if (count($values) == 3) {
echo '<div class="trys">' . $value . '</div>';
} else {
echo '<div>' . $value . '</div>';
}
}
echo '</div>';
}
?>
Which worked for me, gave me this nice list/accordion:
http://bruzienesklinika.lt/web/gydytojai/
Now, each person in the category has some articles as posts and I want a list of their articles under their description. (basic Title + exerpt + read more link)
I've tried to do this by using "List category posts" plugin which allows me to use [catlist id=24] shortcode, but the problem is that browser prints it as plain text, source shows [catlist id=24](You can open the most bottom "GYDYTOJA REUMATOLOGĖ" tab to see that). The shortcode does work inside page, which is rendered by single.php, but it does not show when rendered in the loop I gave you in the beginning of the question.
SO, the question is, how do I make the shortcode work in the initial list, where all the categories are listed with posts inside the accordion.
Now it is not the problem of this certain plugin because no shortcodes work in that accordion list.
Or maybe you have an idea how to do this the other way?

Replace value in shortcode with different value in html

I have a shortcode for a CSS accordion. One of the attributes is $open for the checkbox's "checked" value. Right now, if they type open=checked, it will pass checked="checked" and that div will be visible by default. Is there anyway to replace a custom value with the actual html value? For instance, I want the user to be able to use "open=yes" and have it pass "checked=checked" in the HTML.
// TOGGLE BOXES
function sc_tog_boxes( $attr, $content = null ) {
return '<ul class="togboxes">' . $content . '</ul>';
}
add_shortcode('togboxes', 'sc_tog_boxes');
function sc_tog_box( $atts , $content = null ) {
// Attributes
extract( shortcode_atts(
array(
'number' => '1',
'heading' => 'you forgot the heading tag: heading="your heading"',
'open' => '',
), $atts )
);
// Code
return '<li><label for="' . $number . '">' . $heading . ' <span class="toggle-icon">[+/-]</span></label><input type="checkbox" name="a" id="' . $number . '" checked="' . $open . '"><div class="togbox">' . do_shortcode($content) . '</div></li>';
}
add_shortcode( 'togbox', 'sc_tog_box' );
UPDATE: Okay, I need to rephrase this because the presence of the "checked" attribute means "checked" without any parameter anyway. So I need to be able to add "checked" in the html if they just type "open" in the shortcode, but have no checked attribute if they don't type open.
Found the answer:
if($open === 'yes'){
$open = 'checked';
}
else {
$open = '';
}

Image in recent post of Wordpress Q and A theme

i am using Instant-QA theme, need to update the recent Post widget with image of the user who has asked the questions. I am using the below code in functions.php of subdomain of wordpress website. Currently its showing the simple post--- Any guess in below code-- ?
function print_requested_template_part() {
// Respond only to requests from the same address...
if ( $_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['including_template_part']) && isset($_GET['load_part']) && $_GET['load_part'] != '' ) {
$part = $_GET['load_part'];
$func = 'render_' . str_replace('-', '_', $part); // if you have declared a function called "render_footer_include", then "?load_part=footer_include"
if ( function_exists($func) ) {
// Allow for passing parameters to the function
if ( isset($_GET['params']) ) {
$params = $_GET['params'];
$params = ( strpos($params, ',') !== false )? explode(',', $params) : array($params);
call_user_func_array($func, $params);
} else {
call_user_func($func);
}
}
exit; // if we don't exit here, a whole page will be printed => bad! it's better to have empty footer than a footer with the whole main site...
}
}
add_action('init', 'print_requested_template_part', 1);
function render_my_recent_posts( $numberposts = 5 ) { ?>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ) {
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
</ul><?php
}
DO not waste you time to indulge urself in the above code. Usel below plugin and gets the immediate output.
http://wordpress.org/extend/plugins/recent-comments-with-avatars/ Use this plugin
Thankyou

default="default" for option does not function

Adding the following script to the function.php file in Wordpress:
add_action( 'add_meta_boxes', 'rating_select_box' );
function rating_select_box() {
add_meta_box(
'rating_select_box', // id, used as the html id att
__( 'Select rating:' ), // meta box title, like "Page Attributes"
'rating_select_cb', // callback function, spits out the content
'post', // post type or page. We'll add this to posts only
'side', // context (where on the screen
'low' // priority, where should this go in the context?
);
}
function rating_select_cb( $post )
{
global $wpdb;
$value = get_post_meta($post->ID, 'rating', true);
echo '<div class="misc-pub-section misc-pub-section-last">
<span id="timestamp">'
. '<label>Select a rating:<br></label>';
$selected = ($value == $result->post_name) ? ' selected="selected" ' : null;
echo '<select name="rating">';
echo '<option value="" default="default"> None... </option>';
echo '<option value="0" '.$selected.'> G — Suitable for all audiences </option>';
echo '<option value="1" '.$selected.'> PG — Possibly offensive, usually for audiences 13 and above </option>';
echo '<option value="2" '.$selected.'> R — Intended for adult audiences above 17 </option>';
echo '<option value="3" '.$selected.'> X — Even more mature than above </option>';
echo '</select>';
echo '</span></div>';
}
add_action( 'save_post', 'save_metadata');
function save_metadata($postid)
{
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return false;
if ( !current_user_can( 'edit_page', $postid ) ) return false;
if( empty($postid) ) return false;
if ( is_null($_REQUEST["rating"]) ) {
delete_post_meta($postid, 'rating');
} else {
update_post_meta($postid, 'rating', $_REQUEST['rating']);
}
}
Will add a box in the post page with a drop down list. I want the default option to be on None... so I added a default="default" to that option, but it does not work. By default, the highest number value is selected, in this case, it is X — Even more mature than above.
What am I doing wrong? How can I make it so that the None... option is selected by default?
In a select list, the correct way to "select" an option is with selected="selected", not default="default". Changing your 'None' option to the following should fix it:
echo '<option value="" selected="selected"> None... </option>';
However, you're not dynamically creating your select list, you're just outputting a full list and you'll run into issues selecting the other values too. To fix this, if the options won't be changing, you can put them in an array to loop through them. You can modify your rating_select_cb() method with the following new code to achieve this:
function rating_select_cb( $post ) {
global $wpdb;
$value = get_post_meta($post->ID, 'rating', true);
echo '<div class="misc-pub-section misc-pub-section-last"><span id="timestamp"><label>Select a rating:<br></label>';
// build an array of each available rating
$ratings = array(
1 => 'G — Suitable for all audiences',
2 => 'PG — Possibly offensive, usually for audiences 13 and above',
3 => 'R — Intended for adult audiences above 17',
4 => 'X — Even more mature than above'
);
echo '<select name="rating">';
echo '<option value=""' . ((($value == '') || !isset($ratings[$value])) ? ' selected="selected"' : '') . '> None... </option>';
// output each rating as an option
foreach ($ratings as $id => $text) {
echo '<option value="' . $id . '"' . (($value == $id) ? ' selected="selected"' : '') . '">' . $text. '</option>';
}
echo '</select>';
echo '</span></div>';
}
This method will default-select the "None" option if the selected $value is not in the available list of ratings. After that, it will loop through each rating and output it as an option. If the rating's $id matches the selected $value, it will be marked as selected.
You should use it like this:
echo '<option value="" selected="selected"> None... </option>';

Creating a content rating script

I am trying to write a content rating script where the user can select what type of rating to give to their article (for instance, what age group the articles suits for).
I am using a Wordpress star rating script as a template.
This part of the script is where the user selects the rating:
function pn_apr_meta_box_form( $post )
{
wp_nonce_field( 'pn_apr_meta_box_nonce', 'pn_apr_meta_box_nonce_field' );
$current_post_rating = get_post_meta( $post->ID, PN_APR_RATING_META_KEY, true );
echo '<label for="pn_apr_rating">' . __( 'Choose a rating for this post:', 'author-post-ratings' ) . '</label> ';
echo '<select name="pn_apr_rating" id="pn_apr_rating">';
echo '<option value="unrated"' . selected( $current_post_rating, 0, false ) . '>' . __( 'Unrated', 'author-post-ratings' ) . '</option>';
for ( $i = 1; $i <= 5; $i++ ) {
echo '<option value="' . $i . '"' . selected( $current_post_rating, $i, false ) . '>' . sprintf( _n( '%1s Star', '%1s Stars', $i, 'author-post-ratings' ), $i ) . '</option>';
}
echo '</select>';
}
This part of the script outputs the ratings:
if ( $rating ) {
$output = null;
$output .= '<div class="author-post-rating">';
$output .= '<span class="author-post-rating-label">' . esc_attr( $pn_apr_settings['label_text'] ) . '</span> ';
$output .= '<span class="author-post-rating-stars" title="' . sprintf( __( '%1$d out of %2$d stars', 'author-post-ratings' ), $rating, 5 ) . '">';
// Output active stars
for ( $i = 1; $i <= $rating; $i++ ) {
$output .= '<img src="' . PN_APR_PLUGIN_DIR_URL . 'images/star-active.png" />';
}
// Output inactive stars
for ( $i = $rating + 1; $i <= 5; $i++ ) {
$output .= '<img src="' . PN_APR_PLUGIN_DIR_URL . 'images/star-inactive.png" />';
}
$output .= '</span>' . "\n";
$output .= '</div><!-- .author-post-rating -->';
if ( true == $return ) { return $output; }
// We don't need to use "else" here, since calling return will automatically stop further execution of this function.
echo $output;
}
Now, I want to change this script so that it becomes a content rating script (rather than star rating one). I want to offer these choices for the user:
G — Suitable for all audiences
PG — Possibly offensive, usually for audiences 13 and above
R — Intended for adult audiences above 17
X — Even more mature than above
Question: How can I change the script so that if the user selects for instance PG, then it will output the text Suitable for age 13 and up.
EDIT:
To Shawn, observe the following code:
function rating_select_cb( $post ) {
global $wpdb;
$value = get_post_meta($post->ID, 'rating', true);
echo '<div class="misc-pub-section misc-pub-section-last"><span id="timestamp"><label>Select a rating:<br></label>';
// build an array of each available rating
$ratings = array(
1 => 'G — Suitable for all audiences',
2 => 'PG — Possibly offensive, usually for audiences 13 and above',
3 => 'R — Intended for adult audiences above 17',
4 => 'X — Even more mature than above'
);
echo '<select name="rating">';
echo '<option value=""' . ((($value == '') || !isset($ratings[$value])) ? ' selected="selected"' : '') . '> None... </option>';
// output each rating as an option
foreach ($ratings as $id => $text) {
echo '<option value="' . $id . '"' . (($value == $id) ? ' selected="selected"' : '') . '">' . $text. '</option>';
}
echo '</select>';
echo '</span></div>';
}
Here's something that should get you to where you need to be:
Add to your functions.php:
add_action( 'add_meta_boxes', 'rating_select_box' );
function rating_select_box() {
add_meta_box(
'rating_select_box', // id, used as the html id att
__( 'Select rating:' ), // meta box title, like "Page Attributes"
'rating_select_cb', // callback function, spits out the content
'post', // post type or page. We'll add this to posts only
'side', // context (where on the screen
'low' // priority, where should this go in the context?
);
}
function rating_select_cb( $post )
{
global $wpdb;
$value = get_post_meta($post->ID, 'rating', true);
echo '<div class="misc-pub-section misc-pub-section-last">
<span id="timestamp">'
. '<label>Select a rating:<br></label>';
$selected = ($value == $result->post_name) ? ' selected="selected" ' : null;
echo '<select name="rating">';
echo '<option value="" default="default"> None... </option>';
echo '<option value="0" '.$selected.'> G — Suitable for all audiences </option>';
echo '<option value="1" '.$selected.'> PG — Possibly offensive, usually for audiences 13 and above </option>';
echo '<option value="2" '.$selected.'> R — Intended for adult audiences above 17 </option>';
echo '<option value="3" '.$selected.'> X — Even more mature than above </option>';
echo '</select>';
echo '</span></div>';
}
add_action( 'save_post', 'save_metadata');
function save_metadata($postid)
{
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return false;
if ( !current_user_can( 'edit_page', $postid ) ) return false;
if( empty($postid) ) return false;
if ( is_null($_REQUEST["rating"]) ) {
delete_post_meta($postid, 'rating');
} else {
update_post_meta($postid, 'rating', $_REQUEST['rating']);
}
}
The above code does this:
1. Adds a new metabox to your posts
2. Adds a select box with the rating values
3. Saves the metadata with the post
To access your metadata in your templates:
$meta = get_post_custom($post->ID);
echo $meta['rating'][0];
To have your template display a custom string use something like:
switch ( $meta['rating'][0] ) {
case 0:
echo "This is rated PG";
break;
case 1:
echo "This is rated G";
break;
case 2:
echo "This is rated R";
break;
case 3:
echo "Ug oh! This is rated X!";
break;
default:
echo "This is not yet rated.";
}
**Edit: This code provides full functionality.. you could abandon your current solution if it works for you

Categories