Wordpress save wp_editor content using settings API - wordpress

I'm creating a plugin with an admin settings page, and I want to use the settings API.
I am able to save text fields and checkboxes, but when I add a settings field with a wp_editor it's not saving..?
I used to do this with get_option, but now I want to use a settings class and the register_setting() method.
This is my code:
public function register_settings() {
register_setting( 'eman_setting', 'eman_setting', array( $this, 'eman_validate_settings' ) );
add_settings_field(
'eman_dashboard_welcome',
__( "", 'emanlang' ),
array( $this, 'eman_dashboard_welcome_callback' ),
'management-settings',
'eman_settings_section'
);
}
public function eman_dashboard_welcome_callback() {
//$content = 'Empty';
$editor_id = 'textareadashboardwelcome';
$args = array('textarea_name' => 'eman_dashboard_welcome');
if(! empty( $this->eman_setting['eman_dashboard_welcome'] ) ) {
$content = $this->eman_setting['eman_dashboard_welcome'];
} else {
$content = 'The field is empty';
}
wp_editor( $content, $editor_id, $args );
/** TESTING **/
echo '<br /><b>testing textarea output: </b>'. $content .'<br /><br />';
echo '<b>Complete settings array dump: </b><br />';
echo var_dump($this->eman_setting);
}
Note: This is only the relevant part of the code. On this page I have multiple 'add_settings_field' which are all working fine.
As you may have noticed, for testing I do a var_dump() to check what's inside the options array.
The dump returns:
array(3) { ["eman_opt_in"]=> string(2) "on" ["eman_sample_text"]=> string(10) "sample 1.1" ["eman_sample_text2"]=> string(10) "sample 2.2" }
After saving the form, the array only contains 3 fields, so the array is not even populated with the [eman_dashboard_welcome]?
I tried many possible solutions, like adding this jQuery:
$('#submit').mousedown( function() {
tinyMCE.triggerSave();
});
But nothing works... Please help :-)

Found it..
Solution:
Textarea / wp_editor 'name' needs to call the field in the array.
In my case:
$args = array('textarea_name' => 'eman_setting[eman_dashboard_welcome]');
wp_editor( $content, $editor_id, $args );

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

Woocommerce ajax call on single product page

I get all my products from an API and those who are variations to each other all share a custom meta key called "api_product_family". The products with the same api_product_family are variants to each other, so on the single page I have a hook where I display the other variants with image and anchor to it's variants.
My code:
function mv_variations() {
global $post;
global $wpdb;
$product_id = $post->ID;
$product_family = get_post_meta( $post->ID, 'api_product_family', true );
if(!empty($product_family)) {
$query = "
SELECT post_id
FROM " . $wpdb->prefix . "postmeta
WHERE meta_value = '" . $product_family . "'
";
$products = $wpdb->get_col($query);
if(count($products) > 0) {
for($i=0; $i<count($products); $i++) {
if($products[$i] == $product_id) {
unset($products[$i]);
}
}
if(count($products) > 0) {
print '<h3>Choose other variants: </h3>';
foreach($products as $product) {
$image = wp_get_attachment_image_src(get_post_thumbnail_id($product));
print '<img src="' . $image[0] . '" alt="img"/> ';
}
}
}
}
}
add_action( 'woocommerce_single_product_summary', 'mv_variations' );
The problem:
I have a LOT of posts, and a lot of post_meta's, so it's taking an eternity to load so I was thinking to move this whole function inside and AJAX call so it's doesn't slow down the initial load. The problem is that I have no idea how to do that with wordpress
Are you simply looking to run a WP function via AJAX?
1) Add ajax actions
This needs to run inside the main plugin file. If you run this only on the public code, it will not work. WP is a little weird and all ajax uses admin-ajax.php
if ( wp_doing_ajax() ){
add_action( 'wp_ajax_yourcustomfunction', array($this, 'yourcustomfunction') );
add_action( 'wp_ajax_nopriv_yourcustomfunction', array($this, 'yourcustomfunction') );
}
function yourcustomfunction(){
echo 'success';
exit();
}
2) In JavaScript
in the backend, you have the global: ajaxurl for the ajax url
BUT in the front end you need to pass this as a variable via wp_localize_script
$datatoBePassed = array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
);
wp_localize_script( 'your_javascript_script', 'plugin_display_settings', $datatoBePassed );
In JS:
var datavar = {
action: 'yourcustomfunction',
};
$.post(plugin_display_settings.ajaxurl, datavar, function(response){
//response received here. It will be 'success' which is echoed in PHP
});
3)
If you also want to run a security nonce check (to check the request truly originates from the WP website, prevents some attacks), it gets a little more complicated:
$datatoBePassed should also include 'security' => wp_create_nonce( 'yourplugin_security_nonce' ),
datavar in JS includes security: plugin_display_settings.security,
Finally, your PHP custom function begins with:
// Check security nonce.
if ( ! check_ajax_referer( 'yourplugin_security_nonce', 'security' ) ) {
wp_send_json_error( 'Invalid security token sent.' );
wp_die();
}
// If security check passed, run further
So I think you might get better performance using WP_Query. Below I converted what you have into a custom WP_Query. May need some slight adjustment but should be the right direction.
function mv_variations() {
global $post_id;
// get current post "product family"
$product_family = get_post_meta( $post_id, 'api_product_family', true );
// build related "product family" products query
$products_query_args = array(
'post_type' => 'product', // may need to update this for your case
'posts_per_page' => -1, // return all found
'post__not_in' => array($post_id), // exclude current post
'post_status' => 'publish',
// use a meta query to pull only posts with same "product family" as current post
'meta_query' => array(
array(
'key' => 'api_product_family',
'value' => $product_family,
'compare' => '='
)
)
);
$products_query = new WP_Query($products_query);
// use "the loop" to display your products
if ( $products_query->have_posts() ) :
print '<h3>Choose other variants: </h3>';
while ( $products_query->have_posts() ) : $products_query->the_post();
print ''. wp_get_attachment_image() .'';
endwhile;
// restore global post
wp_reset_postdata();
endif;
}
add_action( 'woocommerce_single_product_summary', 'mv_variations' );

Using WP_Query() to check if a post exists by slug

I am writing a 404.php for wordpress. I have the plugin 'rolescoper' installed, and some pages require the user be logged in to view. Rolescoper doesn't offer any way to distinguish between a page not found (404) and a permission denied (403).
I've been able to build this functionality into my pages using the following code:
$the_query = new WP_Query ( 'pagename=' . $_SERVER['REQUEST_URI'] );
$is_valid_page = ! empty ( $the_query -> queried_object -> post_title );
But, surprisingly, the same method does does not work for posts:
$args = array (
'post_type' => 'post',
'name' => str_replace ( "/", "", $_SERVER['REQUEST_URI'] )
);
$the_post_query = new WP_Query ( $args );
$is_valid_post = ! empty ( $the_post_query -> queried_object -> post_title );
When I do a var_dump on $the_post_query i get something that shows 0 results found. I am sure that the page I'm checking for exists.
Any idea how to use wp_query() to query for a post by slug?
Thanks!
After digging through the docs, I found that Rolescoper provided a nice function, is_restricted_rs(), for solving this problem:
//get the slug requested
$slug = $_SERVER [ 'REQUEST_URI' ];
//First check if it's a page and restricted
$page_id = get_page_by_path ( $slug )->ID;
$page_restricted = is_restricted_rs ( $page_id );
//Then check if it's a post and restricted
$args = array(
'name' => $slug,
'post_type' => 'post',
'post_status' => 'publish',
'numberposts' => 1
);
$my_posts = get_posts($args);
if ( $my_posts ) {
$post_id = $my_posts[0]->ID;
}
$post_restricted = is_restricted_rs ( $post_id );
//then set $content_restricted for use below
$content_restricted = $post_restricted || $page_restricted;
The rolescoper plugin has become defunct and we developed a solution which does not require any external plugin. Instead, we added some code to our theme and added a custom field to each page that we wanted to restrict access to.
This isn't as robust as rolescoper was, but for our use case it was perfect. We have only a few user classes and so I just hardcode the different classes and that's enough for us. I'm sure a similar solution could be used for more complex cases, especially if you expanded on the custom UI code.
I happened to name the field "dhamma_perms" but you could name it anything you want:
function is_restricted() {
return item_restricted(get_post(), wp_get_current_user());
}
function item_restricted($page, $user) {
$dhamma_perms = get_post_meta($page->ID, "dhamma_perms", true);
$requires_os = $dhamma_perms == "oldstudents";
$requires_worker = $dhamma_perms == "workers";
if (!is_user_logged_in()) {
return $requires_os || $requires_worker;
} else if (get_userdata($user->ID)->user_login == "oldstudent") {
return $requires_worker;
} else {
//dhammaworkers and all named users have full read access
return false;
}
}
I then modified any page which could be restricted to have code like this at the top:
<?php get_header(); ?>
<?php if (is_restricted()) : ?>
<?php show_404(); ?> //I just pasted the full content of our 404 page into a function. The 404 page shows a faux-403 page (WP doesn't have real 403 pages) if the content exists but is restricted.
<?php else: ?>
//show normal page stuff
I also modified the header.php to have a proper title for 404 and 403 pages:
<?php if (is_restricted()) : ?>
<title> <?php echo "Login Required " . get_theme_mod('dhamma_title_separator') . " " . get_bloginfo('name'); ?></title>
<?php else: ?>
<title><?php wp_title( get_theme_mod('dhamma_title_separator'), true, "right" ); bloginfo('name'); ?></title>
<? endif; ?>
Finally, I added a custom UI to posts and pages so it's easy to select permissions:
//Register the permissions metabox for posts and pages
function add_perms_box( $post ) {
$screens = [ 'post', 'page', 'wporg_cpt' ];
foreach ( $screens as $screen ) {
add_meta_box(
'dhamma_perms_box', // Unique ID
'Permissions', // Box title
'perms_box_html', // Content callback, must be of type callable
$screens // Post type
);
}
}
function perms_box_html() {
$value = get_post_meta(get_the_ID(), "dhamma_perms", true);
?>
<select name="dhamma_perms" id="dhamma_perms" class="postbox">
<option value="public" <?php selected($value, 'public');?>>Public</option>
<option value="oldstudents" <?php selected($value, 'oldstudents');?>>Old Students Only</option>
<option value="workers" <?php selected($value, 'workers');?>>Dhamma Workers Only</option>
</select>
<?php
}
add_action('add_meta_boxes', 'add_perms_box');
function dhamma_meta_save( $post_id ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
// Exits script depending on save status
if ( $is_autosave || $is_revision ) {
return;
}
// Checks for input and sanitizes/saves if needed
if( isset( $_POST[ 'dhamma_perms' ] ) ) {
update_post_meta( $post_id, 'dhamma_perms', $_POST[ 'dhamma_perms' ] );
}
}
add_action( 'save_post', 'dhamma_meta_save' );
This created a new dropdown on each page and post for us:
I hope this is helpful for anyone else trying to get some simple permissions on a wordpress site!

WordPress - Add tags taxonomy to comments

I'm working on a project that requires comments to have tags and be searchable by tags. Is there a way to implement it in WP, or should I look for some workaround (like create child post type instead of comments and apply tags to it)?
If there is, how can I do it?
Thank you.
You can use comment meta to store and retrieve tags of a particular comment.
First of all, add the tag field to the comment form and populate the tags. The following code will add a "select" field immediately after comment textarea and populate it with the tags.
add_filter( 'comment_form_defaults', 'change_comment_form_defaults');
function change_comment_form_defaults( $default ) {
$commenter = wp_get_current_commenter();
$out = '<label for="comment_tags">Tags:</label><select name="comment_tags" multiple>';
foreach ( get_tags() as $tag ) {
$out .= '<option value="<?php echo $tag->term_id; ?>"><?php echo $tag->name; ?></option>';
}
$out .= '</select>';
$default[ 'comment_field' ] .= $out;
return $default;
}
The comment_post action is triggered immediately after a comment is stored in the database. You can use it to store post meta.
add_action('comment_post', 'add_tags_to_comment', 10, 2);
function add_tags_to_comment( $comment_ID, $comment_approved ) {
foreach($_POST["comment_tags"] as $comment_tag) {
add_comment_meta( $comment_ID, "comment_tag", $comment_tag );
}
}
Instead of storing the selected tags as an array in a single record, I prefer to store each tag as a separate record. This will make it easier to search the comments based on tags.
When you want to retrieve the tags of a comment, You can get_comment_meta
$tags = get_comment_meta($comment_ID, "comment_tag");
foreach($tags as $tag_id) {
$tag_term = get_term($tag_id, 'post_tag');
echo $tag_term->name;
}
Use WP_Comment_Query to search comments based on tags.
$tags = array(1,32,5,4); /* Replace it with tags you want to search */
$args = array(
'meta_query' => array(
array(
'key' => 'comment_tag',
'value' => $tags,
'compare' => 'IN'
)
)
);
$comment_query = new WP_Comment_Query( $args );
Hope this helped you.

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