There's more...

In this recipe, we used the get_post_meta function to retrieve and display the custom fields for books. A shortcode can be a better solution in many cases for retrieving and displaying custom fields. The non-technical administrators may not be comfortable using PHP code to get the field data. Also, a shortcode gives more flexibility in changing the retrieval method as well as displaying it anywhere on the site. Let's create a simple shortcode using the following code to get and display simple custom field data. The code should be placed at the end of the wpcookbookchapter7.php file:

add_shortcode('wpccp_chapter7_book_field','wpccp_chapter7_book_field');
function wpccp_chapter7_book_field($atts){
$field_value = '';
if(isset($atts['book_id']) && $atts['book_id'] != 0){
$field_value = get_post_meta($atts['book_id'],$atts['field_key'],true);
}
return $field_value;
}

With this, we have added a shortcode for displaying any custom field for the book's custom post type. Inside the shortcode function, we check the availability of book IDs. Then, we use the get_post_meta function with the book ID and book custom field key. These values are passed as shortcode attributes, similar to the following code:

[wpccp_chapter7_book_field book_id=7 field_key='wpccp_book_price' ]

The retrieval method is the same as the one we used in this recipe. However, shortcode adds more flexibility by allowing you to display it anywhere on the site, without needing to use any PHP codes. Also, it makes it easier to use a custom table to store custom field data in the future. We have to only change the code within the shortcode and it will work in all the places where we used the shortcode.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.97.216