Using Custom Meta Box Date in WordPress Loop - php

I'm using the below script in the functions.php file to upload a PDF to a custom post type, however I am unsure of how to then retrieve the PDF URL within the WordPress Loop:
function add_custom_meta_boxes() {
add_meta_box('wp_custom_attachment', 'PDF Newsletter', 'wp_custom_attachment', 'newsletter', 'normal', 'high');
}
add_action('add_meta_boxes', 'add_custom_meta_boxes');
function wp_custom_attachment() {
wp_nonce_field(plugin_basename(__FILE__), 'wp_custom_attachment_nonce');
$html = '<p class="description">';
$html .= 'Upload your PDF here.';
$html .= '</p>';
$html .= '<input type="file" id="wp_custom_attachment" name="wp_custom_attachment" value="" size="25">';
$filearray = get_post_meta( get_the_ID(), 'wp_custom_attachment', true );
$this_file = $filearray['url'];
if($this_file != ""){
$html .= '<div>Current file:<br>"' . $this_file . '"</div>';
}
echo $html;
}
add_action('save_post', 'save_custom_meta_data');
function save_custom_meta_data($id) {
if(!empty($_FILES['wp_custom_attachment']['name'])) {
$supported_types = array('application/pdf');
$arr_file_type = wp_check_filetype(basename($_FILES['wp_custom_attachment']['name']));
$uploaded_type = $arr_file_type['type'];
if(in_array($uploaded_type, $supported_types)) {
$upload = wp_upload_bits($_FILES['wp_custom_attachment']['name'], null, file_get_contents($_FILES['wp_custom_attachment']['tmp_name']));
if(isset($upload['error']) && $upload['error'] != 0) {
wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
} else {
add_post_meta($id, 'wp_custom_attachment', $upload);
update_post_meta($id, 'wp_custom_attachment', $upload);
}
}
else {
wp_die("The file type that you've uploaded is not a PDF.");
}
}
}
function update_edit_form() {
echo ' enctype="multipart/form-data"';
}
add_action('post_edit_form_tag', 'update_edit_form');
Here is the loop I am using, including my failed attempt of adding the PDF url:
<?php
$args = array( 'post_type' => 'newsletter', 'posts_per_page' => 10 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
the_title();
echo '<div class="entry-content">';
the_content(); ?>
<?php
$news_pdf = get_post_meta( $post_id, 'wp_custom_attachment', true );
$news_pdf['url']
?>
<?php echo '</div>';
endwhile;
?>

Please first change $post_id to get_the_ID() within your loop.
Change $news_pdf['url'] to:
echo $news_pdf['url'];
Thanks

Related

Wordpress ACF Get Block Field

I'm running into an issue with ACF, and I just can't figure out what's going on, and nothing on the internet is helping out.
I've added some fields to the Image Slider block:
But no matter what I try inside of our custom block code: image-slider.php I cannot get the values of any of the auto_play fields. get_field always returns null. I know the value is there, because if I dump out get_fields( $postID ), I can see the ['page_builder'][2] element has the value I want. I could get to it that way, but I can't seem to determine which index I'm on (the 2) programmatically.
So if you know either, how I can access the field directly, or figure out my current 'page_builder' index, that would be extremely helpful.
It's super confusing, because the have_rows( 'slide_setting' ) call obviously knows where to look, and works as expected.
The custom block php looks like:
<?php
if(have_rows( 'slide_setting' ) ) {
$digits = 3;
$randID = rand(pow(10, $digits-1), pow(10, $digits)-1);
echo '<div class="container"><div class="row"><div id="swiper_'.$randID.'" class="col-md-12 wiche-swiper-top-navigation-wrapper">';
echo '<div class="swiper-container wiche-swiper-top-navigation">';
// var_dump( get_fields( get_the_ID() )['page_builder'][2] );
// var_dump( get_post_field( 'auto_play' ) );
// var_dump(get_field('image_slider_settings_auto_play'));
// var_dump(get_row_index());
// var_dump(get_field_objects( $post->ID ));
// var_dump( get_row_index() );
// var_dump( acf_get_field_group( 'slide_setting' ) );
// die();
if ( get_field( 'auto_play' ) ) {
echo '<div class="swiper-wrapper" data-swiper-autoplay="' . get_field( 'auto_play_delay' ) . '" data-swiper-disable-on-interaction="' . get_field( 'auto_play_disable_on_interaction' ) . '">';
} else {
echo '<div class="swiper-wrapper">';
}
while( have_rows( 'slide_setting' ) ) {
the_row();
$title = get_sub_field( 'title' );
$image = get_sub_field( 'image' );
$content = get_sub_field( 'content' );
if ( $image || $content ) {
echo '<div class="swiper-slide swiper-banner-slide swiper-no-swiping">';
if ( $title ) {
echo '<div class="text-center slider-top-title">';
echo $title;
echo '</div>';
}
if ( $image ) {
echo '<div class="banner-image">';
echo wp_get_attachment_image( $image, 'full', '', array( 'loading' => false ) );
echo '</div>';
}
if ( $content ) {
echo '<div class="banner-content">';
echo $content;
echo '</div>';
}
echo '</div>';
}
}
echo '</div>';
echo '</div>';
echo '<div class="swiper-button-next swiper-button-next-outsite">Next</div><div class="swiper-button-prev swiper-button-prev-outsite">Prev</div>';
echo '</div></div></div>';
}
So I wasn't able to get a perfect answer to my question, looks like the API to get what I want doesn't exist (dumb).
What I ended up with - I set up a new function in my theme's functions.php file that looks like the following:
$post_slider_config_index = 0;
function get_the_slider_config( $post_id ) {
global $post_slider_config_index;
$page_builder = get_fields( $post_id )['page_builder'];
$slider_config = null;
foreach ($page_builder as $key => $value) {
if ( $value['acf_fc_layout'] === 'image_slider_settings' ) {
if ( $key > $post_slider_config_index ) {
$slider_config = $value;
$post_slider_config_index = $key;
break;
}
}
}
return $slider_config;
}
And then inside my image-slider.php file I call it like so:
$slider_config = get_the_slider_config( get_the_ID() );
if ( $slider_config[ 'auto_play' ] ) {
echo '<div class="swiper-wrapper" data-swiper-autoplay="' . $slider_config[ 'auto_play_delay' ] . '" data-swiper-disable-on-interaction="' . $slider_config[ 'auto_play_disable_on_interaction' ] . '">';
} else {
echo '<div class="swiper-wrapper">';
}
The $post_slider_config_index variable keeps track of the last index retrieved so that if there are multiple sliders on a page, it'll grab the right one as its rendered.
It's not perfect, it's not super efficient, but it does what I needed. Annoying WP doesn't just give you the information it obviously has already regarding where you are in the page.

Custom meta box upload file

I have a plugin that adds a meta box with file upload form, the plugin works perfectly, displays the link of the image in the meta box (View Image), load the file, and once published the post, it views in the theme. (in the example I'm using an image file):
<?php
/* Plugin Name: Custom Meta Upload Template*/
add_action('post_edit_form_tag', 'post_edit_form_tag');
function post_edit_form_tag() {
echo ' enctype="multipart/form-data"';
}
function custom_upload() {
add_meta_box( 'meta_upload', __( 'Upload Image', 'meta_upload_domain' ),'meta_upload_callback', 'post' );}
add_action( 'add_meta_boxes', 'custom_upload' );
function meta_upload_callback( $post ) {
global $post;
$custom = get_post_custom($post->ID);
$download_image01 = get_post_meta($post->ID, '_image01', true);
echo '<p><label for="document_file">Upload document:</label><br />';
echo '<input type="file" name="document_file" id="document_file" /></p>';
echo '</p>';
if(!empty($download_image01) && $download_image01 != '0') {
echo '<p>View Image</p>';
}
}
function meta_upload_save( $post_id ) {
global $post;
if(strtolower($_POST['post_type']) === 'page') {
if(!current_user_can('edit_page', $post_id)) {
return $post_id;
}
}
else {
if(!current_user_can('edit_post', $post_id)) {
return $post_id;
}
}
if(!empty($_FILES['document_file'])) {
$file = $_FILES['document_file'];
$upload = wp_handle_upload($file, array('test_form' => false));
if(!isset($upload['error']) && isset($upload['file'])) {
$title = $file['name'];
$ext = strrchr($title, '.');
$title = ($ext !== false) ? substr($title, 0, -strlen($ext)) : $title;
$attachment = array(
'post_mime_type' => 'image',
'post_title' => addslashes($title),
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => $post->ID
);
$attach_key = '_image01';
$attach_id = wp_insert_attachment($attachment, $upload['file']);
$existing_download = (int) get_post_meta($post->ID, $attach_key, true);
if(is_numeric($existing_download)) {
wp_delete_attachment($existing_download);
}
update_post_meta($post->ID, $attach_key, $attach_id);
}
}
}
add_action( 'save_post', 'meta_upload_save' );
and he called the file in the theme:
<?php
$download_image01 = get_post_meta($post->ID, '_image01', true);
if(!empty($download_image01) && $download_image01 != '0') { ?>
<div class="section-content">
<img src="<?php echo wp_get_attachment_url($download_image01); ?>" alt="" />
</div>
<?php }?>
I repeat, the plugin works, but the problem is that I can not place a button or a checkbox that deletes the file when, for example, I want to edit the post, and delete the file, and of course the link "View Image" disappears
Any idea!!
Whenever you want to edit these fields echo the value of the custom fields look like this...
<input type="" value="<img src="<?php echo wp_get_attachment_url($download_image01); ?>" alt="" />">
When you edit the post it's get the value and show the uploaded image's to you.
I don't know if that can help, but I use this code to exclude Attachment when I delete a Custom Post:
add_action('before_delete_post', 'delete_all_attached_media');
function delete_all_attached_media($post_id)
{
if (get_post_type($post_id) == "your-custom-post-type") {
$attachments = get_attached_media('', $post_id);
foreach ($attachments as $attachment) {
wp_delete_attachment($attachment->ID, 'true');
}
}
}

Custom wordpress function not showing the right number of posts

I have a custom wordpress function that shows the number of featured recipes. The function works fine when showposts=-1 is in the query. However when I put 'showposts=5' only two of my posts are shown.
Below is my function
function pika_featured_recipes_shortcode() {
ob_start();
echo '<div class="featured-box-heading"> Featured Recipes </div>';
echo '<div class="featured-box">';
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->query('showposts=5&post_type=cp_recipe&order=Desc&orderby=date' . '&paged=' . $paged);
while ($wp_query->have_posts()):
$wp_query->the_post();
$entry_id = get_the_ID();
$entry_link = get_permalink($entry_id);
$entry_image = get_post_thumbnail_id($entry_id);
$entry_title = get_the_title($entry_id);
$entry_description = get_post_meta($entry_id, '_cp_recipe_short_description', true);
$entry_excerpt = get_post_meta($entry_id, '_cp_recipe_excerpt', true);
$likes = get_post_meta( $entry_id, '_cp_likes', true );
if (get_field('featured-pika-recipe') == 'Yes') {
echo '<div class="featured-result-box item ">
<div class="box">
<div class="pika-featured-box-img">';
if(!empty($entry_image)) {
echo ''.wp_get_attachment_image($entry_image, 'cp_298_192').'';
}
echo' </div><!-- /.box-img -->';
echo'<div class="box-entry">
<h5 class="pika-featured-title"><a href="';
echo $entry_link;
echo '">';
echo $entry_title;
echo'</a></h5>';
echo $trimmed = wp_trim_words( $entry_description, $num_words = 15, $more = null );
echo'</div><!-- /.box-entry -->';
echo'</div>';
echo'</div>';
echo'<div style="clear:both"></div>';
}
endwhile;
wp_reset_query();
echo '</div>';
$output = ob_get_clean();
return $output;}
add_shortcode( 'pika_featured-recipes', 'pika_featured_recipes_shortcode' );
The problem seems to be with
if (get_field('featured-pika-recipe') == 'Yes') {
removing this and the number of posts appear fine. Any way i can resolve this?
maybe because only 2 posts ( of the last 5 posts that you actually call ) got
get_field('featured-pika-recipe') == 'Yes'
you can try to add this custom field directly to your query to get last 5 posts with this custom field with following code
'meta_key' => 'featured-pika-recipe',
'meta_value' => 'Yes'

Display an image from a woocoomerce product on a different page and have it update when the variations are edited by user

I'm stuck trying to get my site together in time for our launch.
We've got a wordpress plugin that displays a product based on selected inputs. Each variation has an image which is layered over top of each other and in pNG to create a final picture. It all works well on the product page http://tattersfield.co/online-tailor-store/double-breasted/luciano-79000-1-jacket/ but now I need the image to display in our Composite Product area http://tattersfield.co/online-tailor-store/three-piece-single-breasted-suit/test-3-piece-suit .
This is the code I need to update to display the plugin generated image instead of the product thumbnail.
<?php
/**
* Composited Product Image
* #version 3.0.0
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) )
exit;
if ( has_post_thumbnail( $product_id ) ) {
?><div class="composited_product_images"><?php
$image_title = esc_attr( get_the_title( get_post_thumbnail_id( $product_id ) ) );
$image_link = wp_get_attachment_url( get_post_thumbnail_id( $product_id ) );
$image = get_the_post_thumbnail( $product_id, apply_filters( 'woocommerce_composited_product_thumbnail_size', 'shop_catalog' ), array(
'title' => $image_title
) );
echo apply_filters( 'woocommerce_composited_product_image_html', sprintf( '%s', $image_link, $image_title, $image ), $product_id );
?></div><?php
}
And this is a snippet of the code from the plugin that displays the image. What do I need to do to get these 2 pieces to work together to display the image I'm after?
Frontend Single Product Page
============================= */
public function display_product_image() {
global $post, $jckpc_options;
$setImages = get_post_meta( $post->ID, $this->slug.'_images', true );
$defaults = get_post_meta( $post->ID, $this->slug.'_defaults', true );
$querySelectors = $_GET;
if(!empty($querySelectors)) {
$sanitisedQuerySelectors = array();
foreach($querySelectors as $attSlug => $attVal) {
$sanitisedQuerySelectors[$this->sanitise_str($attSlug)] = $this->sanitise_str($attVal);
}
$querySelectors = $sanitisedQuerySelectors;
}
$images = array();
if( $setImages['background'] && $setImages['background'] != '' ) {
$imgSrc = wp_get_attachment_image_src($setImages['background'], apply_filters( 'single_product_large_thumbnail_size', 'shop_single' ));
$images[] = '<img id="'.$this->slug.'_image_background" src="'.$imgSrc[0].'">';
}
$setImages = array_reverse($setImages);
$img_i = 1; foreach($setImages as $attSlug => $attVals) {
$default = ( isset($defaults[$attSlug]) && isset($setImages[$attSlug][$defaults[$attSlug]]) ) ? $setImages[$attSlug][$defaults[$attSlug]] : false;
$default = ( isset($querySelectors[$attSlug]) && isset($setImages[$attSlug][$querySelectors[$attSlug]]) ) ? $setImages[$attSlug][$querySelectors[$attSlug]] : $default;
$images[$img_i] = '<div id="'.$this->slug.'_image_'.$attSlug.'">';
if($default) {
$imgSrc = wp_get_attachment_image_src($default, apply_filters( 'single_product_large_thumbnail_size', 'shop_single' ));
$images[$img_i] .= '<img src="'.$imgSrc[0].'">';
}
$images[$img_i] .= '</div>';
$img_i++;
}
// output images
echo '<style>';
echo '#jckpc_images {';
// width
echo "width: {$jckpc_options['image_container_width']['width']};";
// align
if($jckpc_options['image_container_align'] == "centre") {
echo "margin-left: auto; margin-right: auto;";
$jckpc_options['image_container_align'] = "none";
}
echo "float: {$jckpc_options['image_container_align']};";
// spacing
echo "margin-top: {$jckpc_options['image_container_margin']['margin-top']};";
echo "margin-right: {$jckpc_options['image_container_margin']['margin-right']};";
echo "margin-bottom: {$jckpc_options['image_container_margin']['margin-bottom']};";
echo "margin-left: {$jckpc_options['image_container_margin']['margin-left']};";
// padding
echo "padding-top: {$jckpc_options['image_container_padding']['padding-top']};";
echo "padding-right: {$jckpc_options['image_container_padding']['padding-right']};";
echo "padding-bottom: {$jckpc_options['image_container_padding']['padding-bottom']};";
echo "padding-left: {$jckpc_options['image_container_padding']['padding-left']};";
// background
echo "background: {$jckpc_options['image_container_background']};";
echo '}';
$horThumbSpacing = $jckpc_options['thumb_spacing']/2;
$verThumbSpacing = $jckpc_options['thumb_spacing'];
echo "#jckpc_thumbnails {";
echo "margin: {$verThumbSpacing}px -{$horThumbSpacing}px -{$verThumbSpacing}px;";
echo "}";
echo '#jckpc_thumbnails a {';
echo "float: left;";
echo "display: inline;";
$thumbWidth = 100/(int)$jckpc_options['thumb_cols_rows'];
echo "width: {$thumbWidth}%;";
// spacing
echo "padding: 0 {$horThumbSpacing}px {$verThumbSpacing}px;";
echo '}';
echo "#jckpc_image_wrap #jckpc_loading {";
// background
echo "background: {$jckpc_options['loading_overlay_colour']};";
echo "}";
echo "#jckpc_image_wrap #jckpc_loading i {";
$loadingIconMTop = 20/2;
echo "font-size: 20px;";
echo "line-height: 20px;";
echo "margin-top: -{$loadingIconMTop}px;";
echo "color: {$jckpc_options['loading_icon_colour']};";
echo "}";
// breakpoint
if($jckpc_options['enable_breakpoint']) {
echo "#media (max-width: {$jckpc_options['breakpoint']['width']}) {";
echo '#jckpc_images {';
// width
echo "width: {$jckpc_options['image_container_width_breakpoint']['width']};";
// align
if($jckpc_options['image_container_align_breakpoint'] == "centre") {
echo "margin-left: auto; margin-right: auto;";
$jckpc_options['image_container_align_breakpoint'] = "none";
}
echo "float: {$jckpc_options['image_container_align_breakpoint']};";
// spacing
echo "margin-top: {$jckpc_options['image_container_margin_breakpoint']['margin-top']};";
echo "margin-right: {$jckpc_options['image_container_margin_breakpoint']['margin-right']};";
echo "margin-bottom: {$jckpc_options['image_container_margin_breakpoint']['margin-bottom']};";
echo "margin-left: {$jckpc_options['image_container_margin_breakpoint']['margin-left']};";
echo "}";
echo "}";
}
echo '</style>';
echo '<div id="'.$this->slug.'_images">';
echo '<div id="'.$this->slug.'_image_wrap" data-loading="0">';
foreach($images as $image) {
echo $image;
}
echo '<div id="'.$this->slug.'_loading"><i class="jckpc-icn-'.$jckpc_options['loading_icon'].' animate-spin"></i></div>';
echo '</div>';
if($jckpc_options['show_thumbs']) $this->get_thumbnails();
echo '</div>';
}
public function get_thumbnails() {
global $post, $product, $woocommerce;
$attachment_ids = $product->get_gallery_attachment_ids();
if ( $attachment_ids ) {
echo '<div id="'.$this->slug.'_thumbnails">';
$loop = 0;
$columns = apply_filters( 'woocommerce_product_thumbnails_columns', 3 );
foreach ( $attachment_ids as $attachment_id ) {
$classes = array( 'zoom' );
if ( $loop == 0 || $loop % $columns == 0 )
$classes[] = 'first';
if ( ( $loop + 1 ) % $columns == 0 )
$classes[] = 'last';
$image_link = wp_get_attachment_url( $attachment_id );
if ( ! $image_link )
continue;
$image = wp_get_attachment_image( $attachment_id, apply_filters( 'single_product_small_thumbnail_size', 'shop_thumbnail' ) );
$image_class = esc_attr( implode( ' ', $classes ) );
$image_title = esc_attr( get_the_title( $attachment_id ) );
echo apply_filters( 'woocommerce_single_product_image_thumbnail_html', sprintf( '%s', $image_link, $image_class, $image_title, $image ), $attachment_id, $post->ID, $image_class );
$loop++;
}
echo '</div>';
}
}
public function get_image_data($pid, $atts) {
$imgData = array(
'prodid' => $pid
);
if(!empty($atts)){
foreach($atts as $attSlug => $attVal) {
if(substr($attSlug, 0, 10) != "attribute_") $attSlug = 'attribute_'.$attSlug;
$imgData[$attSlug] = sanitize_title_with_dashes($attVal);
}
}

How can I add Wordpress plugin hook to index.php?

I'm using a plugin called Category Thumbnail list. I normally would place the hook [categorythumbnaillist 100] on my Wordpress pages. How can I add this to an actual php page?
http://wordpress.org/extend/plugins/categoy-thumbnail-list/
Plugin code:
$categoryThumbnailList_Order = stripslashes( get_option( 'category-thumbnail-list_order' ) );
if ($categoryThumbnailList_Order == '') {
$categoryThumbnailList_Order = 'date';
}
$categoryThumbnailList_OrderType = stripslashes( get_option( 'category-thumbnail-list_ordertype' ) );
if ($categoryThumbnailList_OrderType == '') {
$categoryThumbnailList_OrderType = 'DESC';
}
$categoryThumbnailList_Path = get_option('siteurl')."/wp-content/plugins/categoy-thumbnail-list/";
define("categoryThumbnailList_REGEXP", "/\[categorythumbnaillist ([[:print:]]+)\]/");
define("categoryThumbnailList_TARGET", "###CATTHMBLST###");
function categoryThumbnailList_callback($listCatId) {
global $post;
global $categoryThumbnailList_Order;
global $categoryThumbnailList_OrderType;
$tmp_post = $post;
$myposts = get_posts('numberposts=-1&&category='.$listCatId[1].'&&orderby='.$categoryThumbnailList_OrderType.'&&order='.$categoryThumbnailList_Order);
$output = '<div class="categoryThumbnailList">';
foreach($myposts as $post) :
setup_postdata($post);
if ( has_post_thumbnail() ) {
$link = get_permalink($post->ID);
$thmb = get_the_post_thumbnail($post->ID,'thumbnail');
$title = get_the_title();
$output .= '<div class="categoryThumbnailList_item">';
$output .= '' .$thmb . '<br/>';
$output .= '' .$title . '';
$output .= '</div>';
}
endforeach;
/*
$output .= '</div>';
$output .= '<div class="categoryThumbnailList_clearer"></div>';
return ($output);
$output = '';
$post = $tmp_post;
setup_postdata($post);
*/
$output .= '</div>';
$output .= '<div class="categoryThumbnailList_clearer"></div>';
$post = $tmp_post;
wp_reset_postdata();
return ($output);
$output = '';
}
function categoryThumbnailList($content) {
return (preg_replace_callback(categoryThumbnailList_REGEXP, 'categoryThumbnailList_callback', $content));
}
function categoryThumbnailList_css() {
global $categoryThumbnailList_Path;
echo "
<style type=\"text/css\">
#import url(\"".$categoryThumbnailList_Path."categoy-thumbnail-list.css\");
</style>
";
}
add_action('wp_head', 'categoryThumbnailList_css');
add_filter('the_content', 'categoryThumbnailList',1);
?>
i think you want to add short-code in template file. place this line in your index.php
<?php echo do_shortcode( '[categorythumbnaillist 100]' ); ?>

Categories