Wordpress Create Custom Comment Type - wordpress

I have a page when I want multiple comment_template, so I want each of my comment_template to have different type so I see different comments in those 2.
My get_comments look like this
$args = array(
'post_id' => get_the_ID(),
'orderby' => 'comment_date',
'order' => 'ASC',
'type' => 'tips'
);
$comments = get_comments($args);
The problem is when I post the comment, I didn't find how to assign this post type to the comment, so I am not able to show them up with get_comments()
I tried to add my comment form like this but that still dosen't work
$comment_args = array(
'type' => 'tips'
);
comment_form($comment_args);

There are several steps to saving a custom comment type which, by the way, is technically not supported in WordPress as is a custom post type.
A. WordPress has 3 types of comments: ping, trackback, and blank for regular comment.
B. Using this premise of WP allowing a blank field to associate for "normal comment", we can now insert our new CCT using any name we want.
C. You must use comment_form_defaults in a function to define an array outside the comments form and pass it as a parameter. (Otherwise you can alter the $arguments in comment_form($args) directly on callout.)
add_filter('comment_form_defaults', 'wpse33967503_defaults_comments_positive');
function wpse33967503_defaults_comments_positive($default)
{
global $comment_id;
$actnonce = 'action_tips';
$action = empty( $_REQUEST['action_tips'] )
? false : $_REQUEST['action_tips'];
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $action != false )
{
if( isset( $_POST['custom_tips'] ) ){
$ctype = $_POST['custom_tips'];
$default['fields']['comment_type'] = '<p class="comment-form-tips '. $ctype .'">
<input type="hidden" name="action_tips" value="'. $actnonce .'"
id="action_tips" />
<input type="hidden" name="comment_type" value="'. $ctype .'"
id="comment_type" /></p>';
}
}
return $default;
}
D. Now we can inject this input into the comment form, but validation is always a good thing.
add_filter( 'preprocess_comment', 'wpse33967503_preprocess_comment_handler', 12, 1 );
function wpse33967503_preprocess_comment_handler( $commentdata )
{
if( ( isset( $_POST['comment_type'] ) ) && ( $_POST['comment_type'] != '') ) {
$commentdata['comment_type'] = wp_filter_nohtml_kses( $_POST['comment_type'] );
}
return $commentdata;
}
Feel free to add messages or even a admin validation... I am just checking that it gets posted.
Your CCT is now part of the commentdata (not comment_meta). this is the regular comment data parameters that are inherit of WP.
Here are the default comment data sets in wp_comments table. Technically you could custom type just about any of these.
comment_ID: ID for the comment
comment_post_ID: The post for which the comment is posted
comment_author: Comment author name
comment_author_email: Author name for the comment
comment_author_url: Author url
comment_author_IP: Author IP address
comment_date: Comment Date
comment_date_gmt: GMT time of the comment
comment_content: Contents of the comment (comment body)
comment_karma: Is there default karma calculation? Maybe rating?
comment_approved: Flag for the comment status.
comment_agent:
comment_type: functionality can be used like custom post type
comment_parent: For threaded comment
user_id: user id if comment author is a registered user of the site.

Related

how to change edit url with "Id" to edit url with "Slug" in Wordpress

I have this is WordPress Post editing Url:
https://example.com/wp-admin/post.php?post=ID&action=edit
and I want to change it to Slug Not the ID Like This:
https://example.com/wp-admin/post.php?post=Slug&action=edit
I was trying to edit the post with this Url but is not working:
https://example.com/wp-admin/post.php?post=MyPostSlug&action=edit
In order to change the edit post link structure, you can use the get_edit_post_link filter like so:
add_filter( 'get_edit_post_link', 'so_73914075_get_edit_post_link', 10, 3);
function so_73914075_get_edit_post_link($link, $post_id, $context) {
$post = get_post( $post_id );
if ( ! in_array( $post->post_type, array( 'post', 'page' ) ) ) {
return $link;
}
$post_type_object = get_post_type_object( $post->post_type );
if ( 'revision' === $post->post_type ) {
$action = '';
} elseif ( 'display' === $context ) {
$action = '&action=edit';
} else {
$action = '&action=edit';
}
if ( 'display' === $context ) {
$post_type = '&post-type=' . $post->post_type;
} else {
$post_type = '&post-type=' . $post->post_type;
}
$custom_edit_link = str_replace( '?post=%d', '?post-name=%s', $post_type_object->_edit_link );
return admin_url( sprintf( $custom_edit_link . $action . $post_type, $post->post_name ) );
}
This will change the edit links for regular posts and pages to something like this:
https://example.com/wp-admin/post.php?post-name=the-post-slug&action=edit&post-type=post
WARNING: make sure you limit this to only the post types you need to change the URL for. Making this change global will almost surely
have unintended effects over other plugins
However, making the admin panel actually load the edit screen is not that easy.
Looking at the source code of the wp-admin/post.php file, you will see that there is no way to hook into the flow and populate the $post_id variable with the post id matching the slug you are sending through.
That means you have 2 options:
RECOMMENDED Update the edit link to whatever format you want and then create an admin redirect function that pulls the slug from the initial URL and redirects to the actual edit page with the ?post=%d in it.
NOT RECOMMENDED Create a new admin edit page that will understand your URL structure and include the wp-admin/post.php after the code that pulls the $post_id based on the slug.
The 2nd method might come with lots of extra code you need to write to cover all the cases and all the instances a post reaches the post.php in the admin panel

WORDPRESS User specific access via ID to specific contact forms CFDB7

I'm trying to implement in the code a way to show specific contact forms data to a particular user via ID but I'm having difficulty finding which part of the code to add it to.
$user_ID = get_current_user_id();
if ( $user_ID == ('2') ) {
I'm currently inside the admin-mainpage.php within the plugin files.
It's not as simple as I thought as it doesn't store the form names via db.
Any help would be appreciated.
Forms-list
It looks like Contact Forms 7 is your plugin for the forms portion while CFDB7 is an accompanying plugin that writes the form submissions to the WP database.
Get the Form ID
There are a couple ways to get the form ID. It looks like the easiest path is to look at the shortcode that the CF7 creates. You can see it in their documentation here. The code is something like [contact-form-7 id="4" title="Foo"] with id being the form ID (4 in this case).
Show the Right Form to the Right Person
Assuming you know the user ids and the related form ids you want to show them, you could write a very simple shortcode plugin to display the right forms for the right people. It'd be something like this untested code below.
//[user-form-display]
function user_form_display( $atts ){
$user_id = get_current_user_id();
if ($user_id == 2){
echo do_shortcode('[contact-form-7 id="4" title="Foo"]');
} else if ($user_id == 4){
echo do_shortcode('[contact-form-7 id="88" title="Bar"]');
}
}
add_shortcode( 'user-form-display', 'user_form_display' );
You could then put the shortcode in the regular post field and not edit either the CF7 plugin nor mess with the theme files.
You could also make the shortcode fancier and tie user ids to form ids directly in the shortcode arguments. That would take a bit more effort but is probably worth it.
Getting the Form Data
You could modify the $args to include form ids based on an association with a user id or multiple user ids. The form ids should be a field in that table. That's the example indicated below.
Alternately you could modify how the information is returned based on the same relationships by setting up the if/then statements in the $data_value lines. This is easier probably but messier in the long run.
function specfic_table_data()
{
global $wpdb;
$user_id = get_current_user_id();
if($user_id == 1){
$form_ids = array(4,6);//only returns forms with id 4 and 6 when it's user w id 1
}
$cfdb = apply_filters( 'cfdb7_database', $wpdb );
$data = array();
$table_name = $cfdb->prefix.'db7_forms';
$args = array(
'post_type'=> 'wpcf7_contact_form',
'order' => 'ASC',
'posts_per_page' => 10,
'post__in' => $form_ids,
);
$the_query = new WP_Query( $args );
while ( $the_query->have_posts() ) : $the_query->the_post();
$form_post_id = get_the_id();
$totalItems = $cfdb->get_var("SELECT COUNT(*) FROM $table_name WHERE form_post_id = $form_post_id");
$title = get_the_title();
$link = "<a class='row-title' href=admin.php?page=cfdb7-list.php&fid=$form_post_id>%s</a>";
$data_value['name'] = sprintf( $link, $title );
$data_value['count'] = sprintf( $link, $totalItems );
$data[] = $data_value;
endwhile;
var_dump($data);
}

Create links for custom field query

All my post has a custom field created_by_alias, I am basically use the value in place of whereever author is used. I have customized the entry-meta function to display this value in plain text, I have also learned to build a query:
$query = new WP_Query( array('meta_key' => 'created_by_alias',
'meta_value' => 'somevalue' ));
Now for the final part: how to create a link for this piece of text, that brings a listing of all posts by this alias?
Do I need to write a template file or is there a quick way to reuse whatever code that generates links to a category, tag listing?
Not sure what you are looking for but seems to me that you want to show a link for the author posts in a specific page, if so, then you can use (using your query)
$query = new WP_Query( array('meta_key'=>'created_by_alias', 'meta_value'=>'somevalue' ));
If $query returns result and you have the id then you can use
echo get_author_posts_url( $query->posts[0]->ID ); // the `ID` from first row
Or for multiple rows, you can loop like
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
echo get_author_posts_url( get_the_ID() ) . '<br />';
}
}
Once this link is clicked, then posts will be retrieved and will be shown according to your page hierarchy, if no author template was found then finally the inedx.php will be used.
Also, if you need a custom template and want to query
$posts = get_posts(array($ID);
Now, to get the id you an use
get_user_by( $field, $value ); // 'id', 'slug', 'email', or 'login'
So, if you have the login name of the user, for example admin then you can use
$id = get_user_by( 'login', 'admin' )->ID; // php 5+
// or
$user = get_user_by( 'login', 'admin' );
$id = $user->ID;
Then get the link and echo it, whereever you want
echo get_author_posts_url( $id );

How can I add/update post meta in a admin menu page?

I wanted to create a plugin to batch manage posts' custom field data. I know I can add post meta by adding a meta box in the post edit screen and using add_action('save_post', 'function_to_update_meta') to trigger add meta functions.
But I don't know how to trigger the add_post_meta function in an admin menu page (such as a custom admin menu). How to do that?
Thank you in advance!
The example given in Wordpress' codex is probably the best and most secure in the way of processing information:
Add Meta Box
Copy and paste it and then fiddle around with it to get a good idea on how to control your posts and pages.
The nice part is that you don't need to worry about checking if you need to Add vs Update a given Post Meta field. Using Update Post Meta will ensure that the proper action is taken for you, even if the field doesn't exist.
The same goes for Update Option if you want to add some global controls that your plugin/theme might use.
BREAKDOWN EXAMPLE:
add_action( 'add_meta_boxes', 'myplugin_add_custom_box' );
add_action( 'save_post', 'myplugin_save_postdata' );
These are the action hooks. The first one is executed when meta boxes are being populated within the post editor, and the second is executed when a post is added OR updated.
function myplugin_add_custom_box()
{
add_meta_box(
'myplugin_sectionid',
__( 'My Post Section Title', 'myplugin_textdomain' ),
'myplugin_inner_custom_box',
'post'
);
add_meta_box(
'myplugin_sectionid',
__( 'My Post Section Title', 'myplugin_textdomain' ),
'myplugin_inner_custom_box',
'page'
);
}
This function is called by the 'add_meta_boxes' action hook. Notice the name of the function and the second argument of the action hook are exactly the same. This registers your meta boxes, which post types they're supposed to appear, and what callback is used to generate the form contained inside.
function myplugin_inner_custom_box( $post )
{
wp_nonce_field( plugin_basename( __FILE__ ), 'myplugin_noncename' );
$value = get_post_meta($post->ID, 'myplugin_new_field') ? get_post_meta($post->ID, 'myplugin_new_field') : 'New Field';
echo '<label for="myplugin_new_field">';
_e("Description for this field", 'myplugin_textdomain' );
echo '</label> ';
echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="'.$value.'" size="25" />';
}
This is the function that is called by the registered meta boxes to generate the form automatically. Notice how the function is called 'myplugin_inner_custom_box' and the 3rd argument in your meta box registration is also called 'myplugin_inner_custom_box'.
The wp_nonce_field() generates a hidden field in your form to verify that data being sent to the form actually came from Wordpress, and can also be used to end the function in case other plugins are using the 'save_post' action hook.
Notice also that the $post object is being passed in as an argument. This will allow you to use certain properties from the post object. I've taken the liberty of checking to see if there is get_post_meta() returns anything with the given post ID. If so, the field is filled with that value. If not, it is filled with 'New Field'.
function myplugin_save_postdata( $post_id )
{
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename( __FILE__ ) ) )
return;
if ( 'page' == $_POST['post_type'] )
{
if ( !current_user_can( 'edit_page', $post_id ) )
return;
}
else
{
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
$mydata = $_POST['myplugin_new_field'];
update_post_meta($post_id, 'myplugin_new_field', $mydata);
}
This is the function that is called by the 'save_post' action hook. Notice how the second argument of the second action hook and this function are both called 'myplugin_save_postdata'. First, there are a series of verifications our plugin must pass before it can actually save any data.
First, we don't want our meta boxes to update every time the given post is auto-updating. If the post is auto-updating, cancel the process.
Secondly, we want to make sure the nonce data is available and verify it. If no nonce data is available or is not verified, cancel the process.
Thirdly, we want to make sure the given user has the edit_page permission. The function first checks the post type, and then checks the appropriate permission. If the user does not have that permission, cancel the process.
Lastly, our plugin has finally been verified and we want to save the information. I took the liberty of adding in the final update_post_meta() line to show you how it all comes together.
Notice how $post_id was passed into the function as an argument. This is one of the pieces needed for the update_post_meta() function. The key was named 'myplugin_new_field' and the value of that metadata is now saved as whatever you input into that custom input field in your custom meta box.
That's about as easy as I can explain the whole process. Just study it, and get your hands dirty with code. The best way to learn is through application rather than theory.
The answer was from the same question I asked somewhere else
And I created my version of example
I added some console.log function for testing, but this is basically doning the same thing as #Chris_() answer:
Menu callback function to generate menu content (PHP):
function ajax_menu_callback() {
?>
<div class="wrap">
<div id="icon-themes" class="icon32"></div>
<h2>Test</h2>
<br />
<form>
<input id="meta" type ="text" name="1" value="<?php echo esc_html( get_post_meta( 1, 'your_key', true) ); ?>" />
<?php submit_button(); ?>
</form>
</div>
<?php
}
Then the javascript to print on the admin side (javascript, don't forget to include a jquery library):
jQuery(document).ready(function() {
$("form").submit(function() {
console.log('Submit Function');
var postMeta = $('input[name="1"]').val();
console.log(postMeta);
var postID = 1;
var button = $('input[type="submit"]');
button.val('saving......');
$.ajax({
data: {action: "update_meta", post_id: postID, post_meta: postMeta, },
type: 'POST',
url: ajaxurl,
success: function( response ) { console.log('Well Done and got this from sever: ' + response); }
}); // end of ajax()
return false;
}); // end of document.ready
}); // end of form.submit
Then the PHP function handle update_post_meta (PHP):
add_action( 'wp_ajax_update_meta', 'my_ajax_callback' );
function my_ajax_callback() {
$post_id = $_POST['post_id'];
$post_meta = $_POST['post_meta'];
update_post_meta( $post_id, 'your_key', $post_meta );
echo 'Meta Updated';
die();
} // end of my_ajax_callback()

wp_update_post make custom field values disappear (Wordpress)

I'm trying to update the post content in one of my post through the wp_update_post function. I have read the documentation here: http://codex.wordpress.org/Function_Reference/wp_update_post
And if I get it right I just need to send the post ID and the post content I want to update with - just like in the example - and this should be the only thing that will change. Although my custom fields that I have attached to this post disappears, strange enough.
I have the following code that I pass on:
if(isset($_POST['submit'])){
$the_post = array();
$the_post['ID'] = $_POST['id'];
$the_post['post_content'] = $_POST['recension'];
// Update the post into the database
wp_update_post( $the_post );
}
How come this happen and how do I solve it?
This is because when you are updating the post the *wp_insert_post* function is used and there is "save_post"(1) action hook which is usually used for saving custom fields data.
The standard way to add/update post meta is something like this:
$post_meta['_mymeta'] = $_POST['_mymeta'];
// Add values of $events_meta as custom fields
foreach ($events_meta as $key => $value) { // Cycle through the $post_meta array!
if( $post->post_type == 'revision' ) return; // Don't store custom data twice
if($value && $value != get_post_meta($post->ID, $key, TRUE)) { // If the custom field already has a value
update_post_meta($post->ID, $key, $value);
} elseif($value && get_post_meta($post_id, $key, TRUE) == "") { // If the custom field doesn't have a value
add_post_meta($post->ID, $key, $value, TRUE);
}
if(!$value) delete_post_meta($post->ID, $key, get_post_meta($post->ID, $key, TRUE)); // Delete if blank
}
...as you can see it is checking for *$_POST* data and if it is empty or not set it updates your meta value with empty data or deletes it completely.
I suppose you should use database update function or some other API function to update post fields...for example this piece of code will update your post menu order:
$wpdb->update( $wpdb->posts, array( 'menu_order' => 5 ), array( 'ID' => $post->ID ) );
(1) Runs whenever a post or page is created or updated, which could be from an import, post/page edit form, xmlrpc, or post by email. Action function arguments: post ID.
To avoid that behavior set false as third parameter.
It deactivates the "after insert hooks".

Resources