I have created gallery metabox but it does not work - wordpress

here is the code which I got from github page:
define('MY_POST_TYPE', 'my');
define('MY_POST_SLUG', 'gallery');
function my_register_post_type () {
$args = array (
'label' => 'Gallery',
'supports' => array( 'title', 'excerpt' ),
'register_meta_box_cb' => 'my_meta_box_cb',
'show_ui' => true,
'query_var' => true
);
register_post_type( MY_POST_TYPE , $args );
}
add_action( 'init', 'my_register_post_type' );
function my_meta_box_cb () {
add_meta_box( MY_POST_TYPE . '_details' , 'Media Library', 'my_meta_box_details', MY_POST_TYPE, 'normal', 'high' );
}
function my_meta_box_details () {
global $post;
$post_ID = $post->ID; // global used by get_upload_iframe_src
printf( "<iframe frameborder='0' src=' %s ' style='width: 100%%; height: 400px;'> </iframe>", get_upload_iframe_src('media') );
}
It shows my gallery page and media up-loader section on that page nicely, but there is no insert into post button inside that uploader and I am unable to insert image to that post. Additionally, If I upload image from my computer it has insert into post button, once I click upon that button page all my media up-loader screen disappears and nothing happens ? what's wrong with my code or approach please

You are missing editor in your supports:
define('MY_POST_TYPE', 'my');
define('MY_POST_SLUG', 'gallery');
function my_register_post_type () {
$args = array (
'label' => 'Gallery',
'supports' => array( 'title', 'excerpt', 'editor' ),
'register_meta_box_cb' => 'my_meta_box_cb',
'show_ui' => true,
'query_var' => true
);
register_post_type( MY_POST_TYPE , $args );
}
add_action( 'init', 'my_register_post_type' );
function my_meta_box_cb () {
add_meta_box( MY_POST_TYPE . '_details' , 'Media Library', 'my_meta_box_details', MY_POST_TYPE, 'normal', 'high' );
}
function my_meta_box_details () {
global $post;
$post_ID = $post->ID; // global used by get_upload_iframe_src
printf( "<iframe frameborder='0' src=' %s ' style='width: 100%%; height: 400px;'> </iframe>", get_upload_iframe_src('media') );
}
Once you add the editor, when you click 'Insert into post' you can see the inserted link in the editor. Which is presumably what you need.
There is a problem with disappearing metabox when you do upload the image.
In my opinion, you don't really need the extra uploader in a metabox. You have 'Add Media' Button above the editor - you can add images, videos or galleries in your CPT that way.
EDIT
You could ditch the media uploader and just call the default wp.media like this:
function my_meta_box_details () {
global $post;
// Here we get the current images ids of the gallery
$custom = get_post_custom($post->ID);
$my_gallery = (isset($custom["my_gallery"][0])) ? $custom["my_gallery"][0] : '';
// We display the gallery
?>
<style>
.gallery-item{
width:150px;
display: inline-block;
margin-right: 10px;
}
.gallery-item img{
width: 150px;
}
</style>
<div class="gallery_images">
<?php
$img_array = (isset($my_gallery) && $my_gallery != '') ? explode(',', $my_gallery) : '';
if ($img_array != '') {
foreach ($img_array as $img) {
echo '<div class="gallery-item">'.wp_get_attachment_image($img).'</div>';
}
}
?>
</div>
<p class="separator">
<input id="my_gallery_input" type="hidden" name="my_gallery" value="<?php echo $my_gallery; ?>" data-urls=""/>
<input id="manage_gallery" title="Manage gallery" type="button" value="Manage gallery" />
<input id="empty_gallery" title="Empty gallery" type="button" value="Empty gallery" />
</p>
<script>
jQuery(document).ready(function($) {
$(document).on('click', '#manage_gallery', upload_gallery_button);
function upload_gallery_button(e) {
e.preventDefault();
var $input_field = $('#my_gallery_input');
var ids = $input_field.val();
var gallerysc = '[gallery ids="' + ids + '"]';
wp.media.gallery.edit(gallerysc).on('update', function(g) {
var id_array = [];
var url_array = [];
$.each(g.models, function(id, img){
url_array.push(img.attributes.url);
id_array.push(img.id);
});
var ids = id_array.join(",");
ids = ids.replace(/,\s*$/, "");
var urls = url_array.join(",");
urls = urls.replace(/,\s*$/, "");
$input_field.val(ids);
var html = '';
for(var i = 0 ; i < url_array.length; i++){
html += '<div class="gallery-item"><img src="'+url_array[i]+'"></div>';
}
$('.gallery_images').html('').append(html);
});
}
$(document).on('click', '#empty_gallery', empty_gallery_button);
function empty_gallery_button(e){
e.preventDefault();
var $input_field = $('#my_gallery_input');
$input_field.val('');
$('.gallery_images').html('');
}
});
</script>
<?php
}
function my_metabox_save(){
global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
return;
} elseif(is_object($post)){
$my_gallery = (isset($_POST['my_gallery'])) ? $_POST['my_gallery'] : '';
update_post_meta($post->ID, 'my_gallery', $my_gallery);
}
}
add_action('save_post', 'my_metabox_save');
And remove the editor from your supports argument. Should be working fine.

Related

Add link to image with Add media

function tshirt_gif_text() {
woocommerce_wp_text_input(
array(
'id' => 'gif_tshirt',
'label' => __( 'GIF T-Shirt', 'woocommerce' ),
'placeholder' => 'http://',
'desc_tip' => 'true',
'description' => __( 'Them GIF links.', 'woocommerce' ),
'value' => get_post_meta( get_the_ID(), 'gif_tshirt', true )
)
);
}
add_action( 'woocommerce_product_options_advanced', 'tshirt_gif_text' );
function tshirt_gif_text_save( $post_id ) {
// update_post_meta( $post_id, 'gif_tshirt', $checkbox );
if (isset($_POST['gif_tshirt'])){
update_post_meta( $post_id, 'gif_tshirt', $_POST['gif_tshirt'], false );
}
if (!isset($_POST['gif_tshirt'])){
delete_post_meta( $post_id, 'gif_tshirt');
}
}
add_action( 'woocommerce_process_product_meta', 'tshirt_gif_text_save' );
I made a custom text field to add a link to a image. I'd like to use the Media uploader to upload or choose an image from the existent ones and update the "gif_tshirt" post meta with the link, but I don't know exactly how to start.
Add my media
I think as a button I can use this one.
And this is the JS
jQuery(function($) {
$(document).ready(function(){
$('#insert-my-media').click(open_media_window);
});
function open_media_window() {
if (this.window === undefined) {
this.window = wp.media({
title: 'Insert a media',
library: {type: 'image'},
multiple: false,
button: {text: 'Insert'}
});
var self = this; // Needed to retrieve our variable in the anonymous function below
this.window.on('select', function() {
var first = self.window.state().get('selection').first().toJSON();
wp.media.editor.insert('[myshortcode id="' + first.id + '"]');
});
}
this.window.open();
return false;
}
});
But it inserts this in the main description, how can i choose the destination?
I did it!
add_action('plugins_loaded', function(){
if($GLOBALS['pagenow']=='post.php'){
add_action('admin_print_scripts', 'my_admin_scripts');
add_action('admin_print_styles', 'my_admin_styles');
}
});
function my_admin_scripts(){
wp_enqueue_script('jquery');
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
}
function my_admin_styles(){
wp_enqueue_style('thickbox');
}
add_action(
'add_meta_boxes',
function(){
add_meta_box(
'my-metaboxx1', // ID
'Hover MP4 Catalog', // Title
'func99999', // Callback (Construct function)
get_post_types(), //screen (This adds metabox to all post types)
'side', // Context
'core'
);
},
999
);
function func99999($post){
$url =get_post_meta($post->ID,'gif_tshirt', true); ?>
<label for="video_URL">
<input id="video_URL" type="text" name="video_URL" value="<?php echo $url;?>" />
<input id="upload_video_button" class="button" type="button" value="Choose a Video" />
<br />Choose a video from the media library then, update your post/page to save it.<br /><br />
<?php
if ($url != "") {
?>
<video class="video" controls>
<source src="<?php echo $url;?>" type="video/mp4" id="vidsrc">
Your browser does not support HTML5 video.
</video>
<?php
}
?>
</label>
<script>
jQuery(document).ready(function($){
$('#video-metabox.postbox').css('margin-top','30px');
var custom_uploader;
$('#upload_video_button').click(function(e) {
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose a Video',
button: {
text: 'Choose a Video'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
$('#video_URL').val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
});
</script>
<?php
}
add_action( 'save_post', function ($post_id) {
if (isset($_POST['video_URL'])){
update_post_meta($post_id, 'gif_tshirt',$_POST['video_URL']);
}
});

Creating image upload widget

I am using wordpress 4.7.2
I am trying to create a simple widget that will only help user to upload an image .
Below my code, when I am selecting an image , it gives me option to insert into post, but I want it not be associated to any post, just want its url and id so that I can use it to display.
I tried to follow use media upload in custom widget and create image uploader widget and wordpress custom widget image uplaaod but could not solved it.
<?php
namespace MyTheme\Widgets;
use \MyTheme\Widgets as Widgets;
class Image extends \WP_Widget {
public function __construct( $id_base = false, $name = false, $widget_options = array(), $control_options = array() ) {
$id_base = ( $id_base ) ? $id_base : 'mytheme-widget-image';
$name = ( $name ) ? $name : __( 'Image', 'mytheme-widget-image-i18n' );
$widget_options = wp_parse_args( $widget_options, array(
'classname' => 'widget_image',
'description' => __( 'An image from the media library', 'mytheme-widget-image-i18n' )
) );
$control_options = wp_parse_args( $control_options, array( 'width' => 300 ) );
parent::__construct( $id_base, $name, $widget_options, $control_options );
add_action('image_widget_print_footer_scripts', array(__CLASS__, 'print_footer_js') );
}
public function widget( $args, $instance ) {
$content = $this->render( $args, $wp_widget );
}
public function render( $args, $instance ){
//generate content
return $content;
}
public function form($instance){
$widget_img_id = isset($instance['widget_img_id']) ? $instance['widget_img_id'] : '';
$image_src = isset($instance['widget-img-id']) ? $instance['widget-img-id'] : '';
$upload_link = esc_url( get_upload_iframe_src( 'image', $widget_img_id ) );
$is_image = ! empty($image_src);
?>
<div class="widget-img-wrapper">
<div class="widget-img-container">
<?php if ( $is_image ): ?>
<img src="<?php echo $image_src; ?>" alt="" style="max-width:100%" />
<?php endif; ?>
<p class="hide-if-no-js">
<a name="upload_img_src" href="<?php echo $upload_link; ?>" class="upload-widget-img <?php if ( $is_image ){ echo 'hidden'; } ?>">
<?php _e('Set custom image') ?>
</a>
<a class="delete-widget-img <?php if ( ! $is_image ) { echo 'hidden'; } ?>"
href="#">
<?php _e('Remove this image') ?>
</a>
<input class="widget-img-id" name="widget_img_id" type="hidden" value="<?php echo esc_attr( $image_id ); ?>" />
</p>
</div>
</div>
<?php
}
public function update( $new_instance, $old_instance ){
$instance = array();
$instance['widget_img_id'] = ( ! empty( $new_instance['widget_img_id'] ) ) ? strip_tags( $new_instance['widget_img_id'] ) : '';
$instance['upload_img_src'] = ( ! empty( $new_instance['upload_img_src'] ) ) ? strip_tags( $new_instance['upload_img_src'] ) : '';
return $instance;
}
public static function print_footer_js()
{
wp_enqueue_media();
?>
<script>
jQuery(function($){
// Set all variables to be used in scope
var frame,
imageContainer = $('.widget-img-wrapper'), // Your meta box id here
addImgLink = imageContainer.find('.upload-widget-img'),
delImgLink = imageContainer.find( '.delete-widget-img'),
imgContainer = imageContainer.find( '.widget-img-container'),
imgIdInput = imageContainer.find( '.widget-img-id' );
// ADD IMAGE LINK
addImgLink.on( 'click', function( event ){
event.preventDefault();
// If the media frame already exists, reopen it.
if ( frame ) {
frame.open();
return;
}
// Create a new media frame
frame = wp.media({
title: 'Select or Upload Media Of Your Chosen Persuasion',
button: {
text: 'Use this media'
},
library: {
type: 'image'
}
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected in the media frame...
frame.on( 'select', function() {
// Get media attachment details from the frame state
var attachment = frame.state().get('selection').first().toJSON();
// Send the attachment URL to our custom image input field.
imgContainer.append( '<img src="'+attachment.url+'" alt="" style="max-width:100%;"/>' );
// Send the attachment id to our hidden input
imgIdInput.val( attachment.id );
// Hide the add image link
addImgLink.addClass( 'hidden' );
// Unhide the remove image link
delImgLink.removeClass( 'hidden' );
});
// Finally, open the modal on click
frame.open();
});
// DELETE IMAGE LINK
delImgLink.on( 'click', function( event ){
event.preventDefault();
// Clear out the preview image
imgContainer.html( '' );
// Un-hide the add image link
addImgLink.removeClass( 'hidden' );
// Hide the delete image link
delImgLink.addClass( 'hidden' );
// Delete the image id from the hidden input
imgIdInput.val( '' );
});
});
</script>
<?php
}
}
I believe, taht "insert into post" is just the default text, and that it doesn't really have anything to do with the post - The file ends up in the media library and in the uploads folders anyway -
function replace_window_text($translated_text, $text) {
if ('Insert into Post' == $text) {
$referer = strpos(wp_get_referer(), 'media_page');
if ($referer != '') {
return __('Upload Billede', 'ink');
}
}
return $translated_text;
}
This is from one of my old projects, where I created a plugin for media uploading. probably doesn't fit your problem, but it can maybe put you on the right path
The issue with this is
add_action('image_widget_print_footer_scripts', array(__CLASS__, 'print_footer_js') ); is unable to enqueue script, neither wp_footer, admin_footer or admin_enqueue_scripts will be able to render script, need to enqueue outside the class. that solves my problem. Do not use this javascript, has problem with instance as used class in js.
<?php
namespace MyTheme\Widgets;
use \MyTheme\Widgets as Widgets;
class Image extends \WP_Widget {
public function __construct( $id_base = false, $name = false, $widget_options = array(), $control_options = array() ) {
$id_base = ( $id_base ) ? $id_base : 'mytheme-widget-image';
$name = ( $name ) ? $name : __( 'Image', 'mytheme-widget-image-i18n' );
$widget_options = wp_parse_args( $widget_options, array(
'classname' => 'widget_image',
'description' => __( 'An image from the media library', 'mytheme-widget-image-i18n' )
) );
$control_options = wp_parse_args( $control_options, array( 'width' => 300 ) );
parent::__construct( $id_base, $name, $widget_options, $control_options );
add_action('image_widget_print_footer_scripts', array(__CLASS__, 'print_footer_js') );
}
public function widget( $args, $instance ) {
$content = $this->render( $args, $wp_widget );
}
public function render( $args, $instance ){
//generate content
return $content;
}
public function form($instance){
$widget_img_id = isset($instance['widget_img_id']) ? $instance['widget_img_id'] : '';
$image_src = isset($instance['widget-img-id']) ? $instance['widget-img-id'] : '';
$upload_link = esc_url( get_upload_iframe_src( 'image', $widget_img_id ) );
$is_image = ! empty($image_src);
?>
<div class="widget-img-wrapper">
<div class="widget-img-container">
<?php if ( $is_image ): ?>
<img src="<?php echo $image_src; ?>" alt="" style="max-width:100%" />
<?php endif; ?>
<p class="hide-if-no-js">
<a name="upload_img_src" href="<?php echo $upload_link; ?>" class="upload-widget-img <?php if ( $is_image ){ echo 'hidden'; } ?>">
<?php _e('Set custom image') ?>
</a>
<a class="delete-widget-img <?php if ( ! $is_image ) { echo 'hidden'; } ?>"
href="#">
<?php _e('Remove this image') ?>
</a>
<input class="widget-img-id" name="widget_img_id" type="hidden" value="<?php echo esc_attr( $image_id ); ?>" />
</p>
</div>
</div>
<?php
}
public function update( $new_instance, $old_instance ){
$instance = array();
$instance['widget_img_id'] = ( ! empty( $new_instance['widget_img_id'] ) ) ? strip_tags( $new_instance['widget_img_id'] ) : '';
$instance['upload_img_src'] = ( ! empty( $new_instance['upload_img_src'] ) ) ? strip_tags( $new_instance['upload_img_src'] ) : '';
return $instance;
}
}
and JS
add_action( 'admin_enqueue_scripts', function(){
wp_enqueue_media('jquery');
} );
add_action('admin_footer', function(){
?>
<script>
jQuery(function($){
// Set all variables to be used in scope
var frame,
imageContainer = $('.widget-img-wrapper'), // Your meta box id here
addImgLink = imageContainer.find('.upload-widget-img'),
delImgLink = imageContainer.find( '.delete-widget-img'),
imgContainer = imageContainer.find( '.widget-img-container'),
imgIdInput = imageContainer.find( '.widget-img-id' );
// ADD IMAGE LINK
addImgLink.on( 'click', function( event ){
event.preventDefault();
// If the media frame already exists, reopen it.
if ( frame ) {
frame.open();
return;
}
// Create a new media frame
frame = wp.media({
title: 'Select or Upload Media Of Your Chosen Persuasion',
button: {
text: 'Use this media'
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected in the media frame...
frame.on( 'select', function() {
// Get media attachment details from the frame state
var attachment = frame.state().get('selection').first().toJSON();
// Send the attachment URL to our custom image input field.
imgContainer.append( '<img src="'+attachment.url+'" alt="" style="max-width:100%;"/>' );
// Send the attachment id to our hidden input
imgIdInput.val( attachment.id );
// Hide the add image link
addImgLink.addClass( 'hidden' );
// Unhide the remove image link
delImgLink.removeClass( 'hidden' );
});
// Finally, open the modal on click
frame.open();
});
// DELETE IMAGE LINK
delImgLink.on( 'click', function( event ){
event.preventDefault();
// Clear out the preview image
imgContainer.html( '' );
// Un-hide the add image link
addImgLink.removeClass( 'hidden' );
// Hide the delete image link
delImgLink.addClass( 'hidden' );
// Delete the image id from the hidden input
imgIdInput.val( '' );
});
});
</script>
<?php
}

WooCommerce Product per page Select option without reload

hi I'm trying without reload Woo-commerce Shop page product per page but its reload of selected number...
Now it's working but page reload then work I need to without reload of shop page
anybody help me
add_action('wp_head','theme_ajaxurl');
function theme_ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
add_action( 'wp_ajax_nopriv_dl_sort_by_page', 'woocommerce_catalog_per_page_ordering' );
add_action( 'wp_ajax_dl_sort_by_page', 'woocommerce_catalog_per_page_ordering' );
function woocommerce_catalog_per_page_ordering() {
?>
<form action="" method="POST" name="results">
<select name="woocommerce-sort-by-columns" id="woocommerce-sort-by-columns" class="sortby">
<?php
// This is where you can change the amounts per page that the user will use feel free to change the numbers and text as you want, in my case we had 4 products per row so I chose to have multiples of four for the user to select.
$shopCatalog_orderby = apply_filters('woocommerce_sortby_page', array(
'' => __('Products per page', 'woocommerce'),
'8' => __('8 per page', 'woocommerce'),
'16' => __('16 per page', 'woocommerce'),
'32' => __('32 per page', 'woocommerce'),
'-1' => __('View All', 'woocommerce'),
));
foreach ( $shopCatalog_orderby as $sort_id => $sort_name )
echo '<option value="' . $sort_id . '" ' . selected( $_SESSION['sortby'], $sort_id, false ) . ' >' . $sort_name . '</option>';
?>
</select>
</form>
<?php // Adrian's code
if (isset($_POST['woocommerce-sort-by-columns']) && (($_COOKIE['shop_pageResults'] <> $_POST['woocommerce-sort-by-columns']))) {
$currentProductsPerPage = $_POST['woocommerce-sort-by-columns'];
} else {
$currentProductsPerPage = $_COOKIE['shop_pageResults'];
}
?>
<script type="text/javascript">
jQuery('select.sortby>option[value="<?php echo $currentProductsPerPage; ?>"]').attr('selected', true);
</script>
<?php
}
// now we set our cookie if we need to
function dl_sort_by_page($count) {
if (isset($_COOKIE['shop_pageResults'])) { // if normal page load with cookie
$count = $_COOKIE['shop_pageResults'];
}
if (isset($_POST['woocommerce-sort-by-columns'])) { //if form submitted
setcookie('shop_pageResults', $_POST['woocommerce-sort-by-columns'], time()+1209600, '/', 'yourdomain.com', false); //this will fail if any part of page has been output- hope this works!
$count = $_POST['woocommerce-sort-by-columns'];
}
// else normal page load and no cookie
return $count;
}
add_filter('loop_shop_per_page','dl_sort_by_page');
Script Code
<script>
jQuery( document ).on( 'change', '#woocommerce-sort-by-columns', function(event) {
event.preventDefault();
var post_id = jQuery('select.sortby').val();
jQuery.ajax({
url : ajaxurl,
type : 'POST',
data : {
action : 'dl_sort_by_page'
},
success : function( response ) {
alert('ok');
}
});
})
</script>

WordPress wp_enqueue_media() upload_mimes not filtering

Using the following code, I'm trying to allow only certain image types to be upload/selected with the WordPress media API. So I'm using add_filter on upload_mimes to restrict the mime types allowed. Using get_allowed_mime_types() I get an array containing only the mime types I want. However, when I click the change image button, I'm still able to upload files of mime types not listed before (such as PDF). What am I doing wrong?
public static function file_uploader( $element_id = null, $multiple = true )
{
add_filter( 'upload_mimes', array( 'JBLAB_Utils', 'images_upload_mimes' ) );
var_dump( get_allowed_mime_types() );
/**
* outputs:
* array(3) {
* ["jpg|jpeg|jpe"]=>
* string(10) "image/jpeg"
* ["gif"]=>
* string(9) "image/gif"
* ["png"]=>
* string(9) "image/png"
* }
*/
$multiple = ( $multiple === true ) ? 'true' : 'false';
wp_enqueue_script('jquery');
wp_enqueue_media();
?>
<div>
<?php
if ( empty( $element_id ) )
{
$element_id = "jblab_uploaded_file_url";
?>
<label for="jblab_uploaded_file_url"><?php _e( 'Image', 'jblab-radionomy' ); ?></label>
<input type="text" name="jblab_uploaded_file_url" id="jblab_uploaded_file_url" class="regular-text">
<?php
}
?>
<input type="button" name="jblab_upload_file_upload_btn" id="jblab_upload_upload_btn" class="button-secondary" value="<?php _e( 'Change Image', 'jblab-radionomy' ); ?>">
</div>
<script type="text/javascript">
jQuery(document).ready(function($){
$('#jblab_upload_upload_btn').click(function(e) {
e.preventDefault();
var image = wp.media({
title: '<?php echo str_replace( "'", "\'", __( 'Change Image', 'jblab-radionomy' ) ); ?>',
multiple: <?php echo $multiple; ?>
}).open()
.on('select', function(e){
var uploaded_image = image.state().get('selection').first();
var image_url = uploaded_image.toJSON().url;
<?php
echo "
if ($('#$element_id').is('img')) {
$('#$element_id').attr('src',image_url);
} else {
$('#$element_id').val(image_url);
}
";
?>
});
});
});
</script>
<?php
}
public static function images_upload_mimes ( $mimes = array() )
{
//unset( $mimes );
$mimes = array(
'jpg|jpeg|jpe' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
);
return $mimes;
}
Ok, so I found a solution to my issue.
I had to move the add_filter outside of the function that is calling the upload API. If anybody has the same problem, try to add_filters as soon as possible in the process, that should do the trick.

Wordpress custom metabox input value with AJAX

I am using Wordpress 3.5, I have a custom post (sp_product) with a metabox and some input field. One of those input (sp_title).
I want to Search by the custom post title name by typing in my input (sp_title) field and when i press add button (that also in my custom meta box), It will find that post by that Title name and bring some post meta data into this Meta box and show into other field.
Here in this picture (Example)
Search
Click Button
Get some value by AJAX from a custom post.
Please give me a example code (just simple)
I will search a simple custom post Title,
Click a button
Get the Title of that post (that i search or match) with any other post meta value, By AJAX (jQuery-AJAX).
Please Help me.
I was able to find the lead because one of my plugins uses something similar to Re-attach images.
So, the relevant Javascript function is findPosts.open('action','find_posts').
It doesn't seem well documented, and I could only found two articles about it:
Find Posts Dialog Box
Using Built-in Post Finder in Plugins
Tried to implement both code samples, the modal window opens but dumps a -1 error. And that's because the Ajax call is not passing the check_ajax_referer in the function wp_ajax_find_posts.
So, the following works and it's based on the second article. But it has a security breach that has to be tackled, which is wp_nonce_field --> check_ajax_referer. It is indicated in the code comments.
To open the Post Selector, double click the text field.
The jQuery Select needs to be worked out.
Plugin file
add_action( 'load-post.php', 'enqueue_scripts_so_14416409' );
add_action( 'add_meta_boxes', 'add_custom_box_so_14416409' );
add_action( 'wp_ajax_find_posts', 'replace_default_ajax_so_14416409', 1 );
/* Scripts */
function enqueue_scripts_so_14416409() {
# Enqueue scripts
wp_enqueue_script( 'open-posts-scripts', plugins_url('open-posts.js', __FILE__), array('media', 'wp-ajax-response'), '0.1', true );
# Add the finder dialog box
add_action( 'admin_footer', 'find_posts_div', 99 );
}
/* Meta box create */
function add_custom_box_so_14416409()
{
add_meta_box(
'sectionid_so_14416409',
__( 'Select a Post' ),
'inner_custom_box_so_14416409',
'post'
);
}
/* Meta box content */
function inner_custom_box_so_14416409( $post )
{
?>
<form id="emc2pdc_form" method="post" action="">
<?php wp_nonce_field( 'find-posts', '_ajax_nonce', false); ?>
<input type="text" name="kc-find-post" id="kc-find-post" class="kc-find-post">
</form>
<?php
}
/* Ajax replacement - Verbatim copy from wp_ajax_find_posts() */
function replace_default_ajax_so_14416409()
{
global $wpdb;
// SECURITY BREACH
// check_ajax_referer( '_ajax_nonce' );
$post_types = get_post_types( array( 'public' => true ), 'objects' );
unset( $post_types['attachment'] );
$s = stripslashes( $_POST['ps'] );
$searchand = $search = '';
$args = array(
'post_type' => array_keys( $post_types ),
'post_status' => 'any',
'posts_per_page' => 50,
);
if ( '' !== $s )
$args['s'] = $s;
$posts = get_posts( $args );
if ( ! $posts )
wp_die( __('No items found.') );
$html = '<table class="widefat" cellspacing="0"><thead><tr><th class="found-radio"><br /></th><th>'.__('Title').'</th><th class="no-break">'.__('Type').'</th><th class="no-break">'.__('Date').'</th><th class="no-break">'.__('Status').'</th></tr></thead><tbody>';
foreach ( $posts as $post ) {
$title = trim( $post->post_title ) ? $post->post_title : __( '(no title)' );
switch ( $post->post_status ) {
case 'publish' :
case 'private' :
$stat = __('Published');
break;
case 'future' :
$stat = __('Scheduled');
break;
case 'pending' :
$stat = __('Pending Review');
break;
case 'draft' :
$stat = __('Draft');
break;
}
if ( '0000-00-00 00:00:00' == $post->post_date ) {
$time = '';
} else {
/* translators: date format in table columns, see http://php.net/date */
$time = mysql2date(__('Y/m/d'), $post->post_date);
}
$html .= '<tr class="found-posts"><td class="found-radio"><input type="radio" id="found-'.$post->ID.'" name="found_post_id" value="' . esc_attr($post->ID) . '"></td>';
$html .= '<td><label for="found-'.$post->ID.'">' . esc_html( $title ) . '</label></td><td class="no-break">' . esc_html( $post_types[$post->post_type]->labels->singular_name ) . '</td><td class="no-break">'.esc_html( $time ) . '</td><td class="no-break">' . esc_html( $stat ). ' </td></tr>' . "\n\n";
}
$html .= '</tbody></table>';
$x = new WP_Ajax_Response();
$x->add( array(
'data' => $html
));
$x->send();
}
Javascript file open-posts.js
jQuery(document).ready(function($) {
// Find posts
var $findBox = $('#find-posts'),
$found = $('#find-posts-response'),
$findBoxSubmit = $('#find-posts-submit');
// Open
$('input.kc-find-post').live('dblclick', function() {
$findBox.data('kcTarget', $(this));
findPosts.open();
});
// Insert
$findBoxSubmit.click(function(e) {
e.preventDefault();
// Be nice!
if ( !$findBox.data('kcTarget') )
return;
var $selected = $found.find('input:checked');
if ( !$selected.length )
return false;
var $target = $findBox.data('kcTarget'),
current = $target.val(),
current = current === '' ? [] : current.split(','),
newID = $selected.val();
if ( $.inArray(newID, current) < 0 ) {
current.push(newID);
$target.val( current.join(',') );
}
});
// Double click on the radios
$('input[name="found_post_id"]', $findBox).live('dblclick', function() {
$findBoxSubmit.trigger('click');
});
// Close
$( '#find-posts-close' ).click(function() {
$findBox.removeData('kcTarget');
});
});

Resources