wp_editer auto echo \ when save code? - wordpress

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

Related

Add different WordPress excerpt formats to different templates

I added the following code to my functions.php file in WordPress 6.1.1 to display excerpts.
function new_excerpt_length($length) {
return 100;
}
add_filter('excerpt_length', 'new_excerpt_length');
function new_excerpt_more($more) {
return '...';
}
add_filter('excerpt_more', 'new_excerpt_more');
...but I also have a use case to show the full excerpt without a read more link.
On page template 1 I add the below code to display the excerpt:
<?php echo the_excerpt(); ?>
...and it displays the excerpt as per the functions.php file but how do I create a 2nd excerpt without the read more link and apply it to page template 2?
Is there a parameter I can use within the_excerpt(parameter); or can I use something like wp_trim_excerpt https://developer.wordpress.org/reference/functions/wp_trim_excerpt/ maybe?
I came across the below code that is supposed to do what I want
function wpex_get_excerpt( $args = array() ) {
// Default arguments.
$defaults = array(
'post' => '',
'length' => 40,
'readmore' => false,
'readmore_text' => esc_html__( 'read more', 'text-domain' ),
'readmore_after' => '',
'custom_excerpts' => true,
'disable_more' => false,
);
// Apply filters to allow child themes mods.
$args = apply_filters( 'wpex_excerpt_defaults', $defaults );
// Parse arguments, takes the function arguments and combines them with the defaults.
$args = wp_parse_args( $args, $defaults );
// Apply filters to allow child themes mods.
$args = apply_filters( 'wpex_excerpt_args', $args );
// Extract arguments to make it easier to use below.
extract( $args );
// Get the current post.
$post = get_post( $post );
// Get the current post id.
$post_id = $post->ID;
// Check for custom excerpts.
if ( $custom_excerpts && has_excerpt( $post_id ) ) {
$output = $post->post_excerpt;
}
// No custom excerpt...so lets generate one.
else {
// Create the readmore link.
$readmore_link = '' . $readmore_text . $readmore_after . '';
// Check for more tag and return content if it exists.
if ( ! $disable_more && strpos( $post->post_content, '<!--more-->' ) ) {
$output = apply_filters( 'the_content', get_the_content( $readmore_text . $readmore_after ) );
}
// No more tag defined so generate excerpt using wp_trim_words.
else {
// Generate an excerpt from the post content.
$output = wp_trim_words( strip_shortcodes( $post->post_content ), $length );
// Add the readmore text to the excerpt if enabled.
if ( $readmore ) {
$output .= apply_filters( 'wpex_readmore_link', $readmore_link );
}
}
}
// Apply filters and return the excerpt.
return apply_filters( 'wpex_excerpt', $output );
}
Output using:
<?php echo wpex_get_excerpt ( $defaults = array(
'length' => 40,
'readmore' => true,
'readmore_text' => esc_html__( 'read more', 'wpex-boutique' ),
'custom_excerpts' => true,
) ); ?>
...but doesn't seem to workas intended. Outputs the excerpt with no link but the args don't see to work when changed. Would be perfect for my use otherwise. Maybe someone sees how to fix this code?
Thanks

Pods Custom Post types use Tags with Check Boxes like Categories

I have been using pods to create various custom post types .. I was able to find some code to do what I want for the Standard wordpress post type .. How can I modify this code to work with my pods post types ?
I wan to Change from having to type the tags to pulling in the tags with check boxes
Like this here
Here is the code `/*
* Meta Box Removal
*/
function rudr_post_tags_meta_box_remove() {
$id = 'tagsdiv-post_tag'; // you can find it in a page source code (Ctrl+U)
$post_type = 'post'; // remove only from post edit screen
$position = 'side';
remove_meta_box( $id, $post_type, $position );
}
add_action( 'admin_menu', 'rudr_post_tags_meta_box_remove');
/*
* Add
*/
function rudr_add_new_tags_metabox(){
$id = 'rudrtagsdiv-post_tag'; // it should be unique
$heading = 'Tags'; // meta box heading
$callback = 'rudr_metabox_content'; // the name of the callback function
$post_type = 'post';
$position = 'side';
$pri = 'default'; // priority, 'default' is good for us
add_meta_box( $id, $heading, $callback, $post_type, $position, $pri );
}
add_action( 'admin_menu', 'rudr_add_new_tags_metabox');
/*
* Fill
*/
function rudr_metabox_content($post) {
// get all blog post tags as an array of objects
$all_tags = get_terms( array('taxonomy' => 'post_tag', 'hide_empty' => 0) );
// get all tags assigned to a post
$all_tags_of_post = get_the_terms( $post->ID, 'post_tag' );
// create an array of post tags ids
$ids = array();
if ( $all_tags_of_post ) {
foreach ($all_tags_of_post as $tag ) {
$ids[] = $tag->term_id;
}
}
// HTML
echo '<div id="taxonomy-post_tag" class="categorydiv">';
echo '<input type="hidden" name="tax_input[post_tag][]" value="0" />';
echo '<ul>';
foreach( $all_tags as $tag ){
// unchecked by default
$checked = "";
// if an ID of a tag in the loop is in the array of assigned post tags - then check the checkbox
if ( in_array( $tag->term_id, $ids ) ) {
$checked = " checked='checked'";
}
$id = 'post_tag-' . $tag->term_id;
echo "<li id='{$id}'>";
echo "<label><input type='checkbox' name='tax_input[post_tag][]' id='in-$id'". $checked ." value='$tag->slug' /> $tag->name</label><br />";
echo "</li>";
}
echo '</ul></div>'; // end HTML
}
`

WooCommerce Hook - woocommerce_after_cart_item_name

I am using a function to add custom meta to products. I have used the following hooks for SHOW on Product Loop woocommerce_after_shop_loop_item and Product Single Page woocommerce_product_meta_end.
So, when applying to get the same results on CART PAGE product/item by using the hook
woocommerce_after_cart_item_name it doesn’t work with no results.
Why isn’t the hook woocommerce_after_cart_item_name working if it works with the other previous hooks mentioned?
This the code I am using. I just change the hook to make it to show in Product Loop and Product Single Page, need it to show on cart Products as well. I was just wondering why it doesn't work with cart item hook..
public function woocommerce_after_cart_item_name()
{
global $product;
if ( !PluginOptions::value('shop_season') && !PluginOptions::value('shop_car_type') )
return;
$product_id = $product->get_id();
$season = get_post_meta( $product_id, 'season', true );
$car_type = get_post_meta( $product_id, 'car_type', true );
$tips_seasons = $this->ui_tips_season();
$tips_car_types = $this->ui_tips_car_types();
?>
<div class="tyre-details tyre-tips">
<?php if ( PluginOptions::value('shop_season') && $season ): ?>
<?php echo $tips_seasons[ strtolower($season) ]; ?>
<?php endif ?>
<?php if ( PluginOptions::value('shop_car_type') && $car_type ): ?>
<?php echo $tips_car_types[ strtolower($car_type) ]; ?>
<?php endif ?>
</div>
<?php
}
It is from a plugin. I was just given this code from woocommerce support but i do not know how to complete it. He says to replace with my meta_keys in the code which I will post below here. Can you help me finish this? or tell me where I need to replace. My meta_keys are $season and $car-type but i don't know how to apply with the code provided by woocommerce.
// Display custom cart item meta data (in cart and checkout)
add_filter( 'woocommerce_get_item_data', 'display_cart_item_custom_meta_data', 10, 2 );
function display_cart_item_custom_meta_data( $item_data, $cart_item ) {
$meta_key = 'PR CODE';
if ( isset($cart_item['add_size']) && isset($cart_item['add_size'] [$meta_key]) ) {
$item_data[] = array(
'key' => $meta_key,
'value' => $cart_item['add_size'][$meta_key],
);
}
return $item_data;
}
// Save cart item custom meta as order item meta data and display it everywhere on orders and email notifications.
add_action( 'woocommerce_checkout_create_order_line_item', 'save_cart_item_custom_meta_as_order_item_meta', 10, 4 );
function save_cart_item_custom_meta_as_order_item_meta( $item, $cart_item_key, $values, $order ) {
$meta_key = 'PR CODE';
if ( isset($values['add_size']) && isset($values['add_size'][$meta_key]) ) {
$item->update_meta_data( $meta_key, $values['add_size'][$meta_key] );
}
}
I located the ClassName (class FeatureTyreTips) and added that to the code you provided. I entered this in functions.php and it said fatal error when loading the cart page. I also tried placing it in the cart.php with same results...and I tried in the same plugin file where this code came from originally. All 3 locations did not work...only difference was that it did not show fatal error when adding and activating your new code in the plugin file when loading cart page. Any ideas? grazie Vdgeatano
The "Fatal Error" is most likely due to the fact that "the non-static method cannot be called statically": PHP - Static methods
I have now corrected the code.
Considering that the class name that was missing in your code is FeatureTyreTips, the correct code to add some text after the product name is:
add_action( 'woocommerce_after_cart_item_name', 'add_custom_text_after_cart_item_name', 10, 2 );
function add_custom_text_after_cart_item_name( $cart_item, $cart_item_key ) {
// create an instance of the "PluginOptions" class
$PluginOptions = new PluginOptions();
if ( ! $PluginOptions->value( 'shop_season' ) && ! $PluginOptions->value( 'shop_car_type' ) ) {
return;
}
$product = $cart_item['data'];
$season = get_post_meta( $product->get_id(), 'season', true );
$car_type = get_post_meta( $product->get_id(), 'car_type', true );
// create an instance of the "FeatureTyreTips" class
$FeatureTyreTips = new FeatureTyreTips();
$tips_seasons = $FeatureTyreTips->ui_tips_season();
$tips_car_types = $FeatureTyreTips->ui_tips_car_types();
if ( ! $PluginOptions->value('shop_season') || ! $season ) {
$season = '';
}
if ( ! $PluginOptions->value('shop_car_type') || ! $car_type ) {
$car_type = '';
}
$html = '<div class="tyre-details tyre-tips">' . trim( $season . ' ' . $car_type ) . '</div>';
echo $html;
}
The code has been tested (where possible) and works.It needs to be added to your theme's functions.php file or in your plugin.

Combine multiple custom user taxonomy in single url

I have created custom user taxonomy for user and its working good for single taxonomy.
From Bellow reference guide i have created custom user taxonomy.
Reference guide:- http://justintadlock.com/archives/2011/10/20/custom-user-taxonomies-in-wordpress
Bellow is structure of taxonomy
(registered taxonomy) profession
Dietitian (under the profession )
(registered taxonomy) city
NewYork(under the city)
my slug name name expert
Here i want to display filter result which user is Dietitian in NewYork city.so it will display all user which have selected above option in profile.
Now i want the url something like www.test.com/expert/dietitian/newyork
with user which have selected Dietitian , NewYork in user profile. And is there any solution to combine Dietitian,NewYork
The url with single terms works like:- www.test.com/expert/dietitian/
I am assuming that you have spend a great deal of time on the tutorial of justintadlock, so I will get involved only with the parts of it that are needed for the multiple taxonomy filtering and display on the front-end.
Before your read the long text, you can have a taste at http://playground.georgemanousarides.com/
So, first thing's first.
The logical base is the same for both SINGLE TAXONOMY and MULTIPLE TAXONOMIES.
After having registered the taxonomies and their terms and have done all the work needed wp-admin wise, we will need:
A) A page (lets call it TAX-QUERY PAGE) in which visitors can select the taxonomy query.
B) Another page (lets call it TAX-RESULTS PAGE) in which the results of TAX-QUERY PAGE will be displayed.
Let's dive in
SINGLE TAXONOMY
TAX-QUERY PAGE
After following the tutorial, the page that you display the taxonomies links should look, on its primal form, like this:
single taxonomy tax-query page
Visitors "Select" which taxonomy they want to see by simply clicking on the links provided.
Note that:
A) The links for:
Proffession will be like:
www.example.com/user/profession/developer/
City will be like:
www.example.com/user/city/gotham/
B) The slugs "user/city" and "user/profession" are defined at the function: my_register_user_taxonomy >> register_taxonomy >> rewrite >> slug
TAX-RESULTS PAGE
Clicking on the links mentioned above takes you to a page ( which needs to be defined by you of course ) that displays all the users under the same taxonomy-term.
This is achieved by creating custom taxonomy templates.
You can create the taxonomy-profession-developer.php file to handle a single taxonomy and term, or the taxonomy-profession.php to handle a single taxonomy and all its' terms, or the taxonomy.php for all taxonomies and their terms.
In my opinion, if you don't want your server to be flooded with template files which are manually created by you, you should use the taxonomy.php and make a general teplate for all taxonomies which descriminates the results you want to display automatically.
Note that:
A) To itterate through users and fetch only those under the desired taxonomy-term, a custom query is needed ( in the taxonomy.php file ), as mentioned and explained in the tutorial.
B) Permalinks should be on Post Name option from the wp-admin >> settings >> permalinks so that wordpress can find your taxonomies, fetch the file taxonomy.php and provide usefull info about the selected taxonomy that can be used in the taxonomy.php file.
MULTIPLE TAXONOMIES
TAX-QUERY PAGE
We need to create a page where visitors will select terms from the custom taxonomies. This page will provide the TAX-RESULTS PAGE ( taxonomy.php ) with the needed terms through a link (as get variables**) so as to make a query.
**In order to have pretty permalinks in the TAX-RESULTS PAGE we need to add the following rewrite function (found it here) to the function.php, and refresh the permalinks in wp-admin:
function eg_add_rewrite_rules() {
global $wp_rewrite;
$new_rules = array(
'user/(profession|city)/(.+?)/(profession|city)/(.+?)/?$' => 'index.php?post_type=eg_event&' . $wp_rewrite->preg_index(1) . '=' . $wp_rewrite->preg_index(2) . '&' . $wp_rewrite->preg_index(3) . '=' . $wp_rewrite->preg_index(4),
'user/(profession|city)/(.+)/?$' => 'index.php?post_type=eg_event&' . $wp_rewrite->preg_index(1) . '=' . $wp_rewrite->preg_index(2)
);
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action( 'generate_rewrite_rules', 'eg_add_rewrite_rules' );
Note that
If you register more taxonomies the "profession|city" in the function should become "profession|city|tax1|tax2|tax3".
So the TAX-QUERY PAGE will be:
HTML
<div id="taxonomies">
<h1>Find your professional</h1>
<form>
<?php if ( $taxonomies = get_object_taxonomies( 'user' ) ) : //get all taxonomies under the object_type "user" ( The second parameter given to the function my_register_user_taxonomy of the tutorial )
foreach ( $taxonomies as $taxonomy ) : ?>
<p>
<ul>
<fieldset id="<?php echo esc_attr( $taxonomy ); ?>"> <!-- group the form by taxonomies -->
<legend><h2>Choose <?php echo $taxonomy; ?></h2></legend>
<?php if ( $terms = get_terms( $taxonomy ) ) : //get taxonomy's terms
foreach ( $terms as $term ) : ?>
<li><input type="checkbox" value="<?php echo esc_attr( $term -> slug ); ?>"> <?php echo $term -> name; ?></li>
<?php endforeach;
endif; ?>
</fieldset>
</ul>
</p>
<?php endforeach;
endif; ?>
</form>
<a id="multiTaxSubmit" href="<?php echo esc_attr( get_home_url() . '/user' ); ?>">SUBMIT</a> <!-- this link is processed by jQuery to provide the taxonomy.php with the proper values. The href attribute is the base url needed by the taxonomy.php -->
</div>
JQUERY ( Can be put in an external file )
$( document ).ready( function() {
$( '#multiTaxSubmit' ).click( function ( event ){
event.preventDefault(); //prevent default link url from loading
var taxQuerySubmit = $( this ),
hasChecked = 0;
querySlug = taxQuerySubmit.attr( 'href' ); //get multitax url base from link href attr
$( '#taxonomies fieldset' ).each( function() { //iterate each taxonomy
var checkedTerms = $( this ).find( 'input:checked' ),
checkedLength = checkedTerms.length; //how many terms has the user selected
if ( checkedLength ) {
hasChecked += checkedLength;
querySlug += '/' + $( this ).attr( 'id' ) + '/'; //add taxonomy slug to query url
checkedTerms.each( function( index, value ) {
var comma = ( index == checkedLength-1 ? '' : ',' );
querySlug += $( this ).val() + comma;
} );
}
} );
if ( hasChecked ) {
window.location = querySlug;
} else {
alert( 'Please enter some criteria.' );
}
} );
} );
TAX-RESULTS PAGE ( taxonomy.php )
<?php
$USERS_BY_TAX = array();
if ( $taxonomies = get_object_taxonomies( 'user' ) ) { //get all taxonomies under the object_type "user" ( The second parameter given to the function my_register_user_taxonomy of the tutorial )
foreach ( $taxonomies as $tax_key => $taxonomy ) {
eval( '$check = $' . $taxonomy . ';' ); // Check if the taxonomy exists in the url. eval outputs $check = $profession, $check = $city etc.
if ( !$check ){
unset( $taxonomies[ $tax_key ] );
continue;
}
eval( '$term_names = explode( ",", $' . $taxonomy . ' );' ); // get terms array from $$taxonomy which gives $profession,$city, the values of which are given through the url as such: $profession="designer,developer"
$USERS_BY_TAX[ $taxonomy ] = array();
foreach ( $term_names as $term_name ) {
$term_obj = get_term_by( 'name', $term_name, $taxonomy ); //get term object for each given term
$users_in_term = get_objects_in_term( $term_obj -> term_id, $taxonomy ); // find users with term
if ( !empty( $users_in_term ) ) {
$USERS_BY_TAX[ $taxonomy ] = $USERS_BY_TAX[ $taxonomy ] + array_fill_keys( $users_in_term, $term_name ) ;
}
}
}
}
/* $USERS_BY_TAX array has all the users for each taxonomy but we only need those who exist in all taxonomies */
if ( $taxonomies ) {
$RESULTS = $USERS_BY_TAX; // keep the initiate array intact
$matched = array_pop( $USERS_BY_TAX ); // first array to compare
$TAXS = $taxonomies;
array_pop( $taxonomies );
if ( !empty( $USERS_BY_TAX ) ) {
foreach ( $taxonomies as $taxonomy ) {
if ( !empty( $USERS_BY_TAX ) ) $matched = array_intersect_key( $matched, $USERS_BY_TAX[ $taxonomy ] );
}
}
}
?>
/* DISPLAY */
<?php if ( $matched ) :
foreach ( array_keys( $matched ) as $user_id ): ?>
<div class="user-entry">
<?php echo get_avatar( get_the_author_meta( 'email', $user_id ), '96' ); ?>
<h2><?php the_author_meta( 'display_name', $user_id ); ?></h2>
<?php if ( in_array( 'profession', $TAXS ) ) : ?><h3>Profession: <?php echo $RESULTS[ 'profession' ][ $user_id ]; ?></h3><?php endif;?>
<?php if ( in_array( 'city', $TAXS ) ) : ?><h3>City: <?php echo $RESULTS[ 'city' ][ $user_id ]; ?></h3><?php endif;?>
<?php echo wpautop( get_the_author_meta( 'description', $user_id ) ); ?>
</div>
<?php endforeach;
else: ?>
<div class="user-entry">
<h2>We are sorry. No results match your criteria.</h2>
<h3>Please go back and search again!</h3>
</div>
<?php endif; ?>
This rewrite rule should work (assuming "profession" and "city" are the taxonomy registered names):
Code:
function custom_rewrite_rules() {
add_rewrite_rule('^profession/(.*)/city/(.*)?', 'index.php?profession=$matches[1]&city=$matches[2]', 'top');
}
add_action('init', 'custom_rewrite_rules');
Remember to flush the rewirte rules after saving this code in your site.
URL :
http://yourdomain.com/profession/dietitian/city/newyork/
To flush the permalinks or rewrite rules from your theme or plugin you need to use the flush_rewrite_rules() function.
<?php
function custom_rewrite_rules() {
flush_rewrite_rules();
add_rewrite_rule( '^products/([^/]*)/([^/]*)/(\d*)?',
'index.php?product_type=$matches[1]&product_brand=$matches[2]&p=$matches[3]',
'top' );
//Post Type: products
//Taxonomy: product_type
//Taxonomy: product_brand
}
add_action('init', 'custom_rewrite_rules');
?>

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