How to add a custom event item in Buddypress Activity Stream? - wordpress

Does anybody know the basic steps on how to add a custom event item to the Buddypress activity stream? I've got a custom post type of "activity" that my members can click on in the post and it records in a database table that that user has "completed" that activity. More or less like a "to do" list. I'm trying to figure out how I can integrate this with the buddypress activity stream so when a user clicks the button, it inserts something like, "John Doe has completed Permalinked Post Title Here." I've looked through the Buddypress codex & have Googled quite a bit, but I can't seem to find any good tutorials on this. If anybody can point me in the right direction or give me a simple plain English step by step I would appreciate it. Please know that I'm not looking for any code written, just a general idea of the steps involved in making this happen.
For anyone who is searching, this is what I wrote in my php file that was called in the ajax request for the button that "completes" the activity...
// Begin Code for Custom Activity Stream
global $wp, $wp_query;
$this_activity_object = get_post( $activity_post_id_complete );
$title = $this_activity_object->post_title;
$activity_content = $title;
$this_user_profile_url = bp_core_get_user_domain($wp_user_id);
$action_String = "#" . bp_core_get_username($wp_user_id)." just completed a custom activity!";
global $bp;
bp_activity_add( array(
'user_id' => $wp_user_id,
'item_id' => $activity_db_id_complete,
'action' => $action_String,
'content' => $activity_content,
'component' => 'activity',
'primary_link' => '' . $title . '',
'type' => 'custom_activity_update',
'hide_sitewide' => false
));

You can use bp_activity_add(). For example, you'd do it like this:
// record an activity item to the activity table
bp_activity_add( array(
'id' => $id
'user_id' => $user_id,
'item_id' => $item_id,
'action' => $action,
'content' => $content,
'component' => $component,
'primary_link' => $link,
'type' => $type,
'secondary_item_id' => $secondary_item_id,
'recorded_time' => $time,
'hide_sitewide' => false,
'is_spam' => $spam
));
Ref explaining what the parameters mean:
http://codex.buddypress.org/developer/function-examples/bp_activity_add/

Related

How to filter custom fields for custom post type in wordpress rest api?

I use wordpress standard with the plugins "Advanced custom fields" and "custom_post_type ui". I created a post_type called deals and added some custom fields with it.
What I need to do now, is filter the results when accessing the rest api like this:
http://localhost:8000/wp-json/wp/v2/deals
Actually I only need the acf part of it. I dont care about the rest.
[{"id":29,"date":"2019-04-12T12:34:14","date_gmt":"2019-04-
12T12:34:14","guid":{"rendered":"http:\/\/localhost:8000\/?
post_type=deals&p=29"},"modified":"2019-04-
12T12:34:14","modified_gmt":"2019-04-12T12:34:14",
"slug":"test-title","status":"publish","type":"deals",
"link":"http:\/\/localhost:8000\/deal s\/test- title\/","template":"",
"meta":[],"tax-deals":[],"acf":{"title":"Title for Deals
Post","description":"","image":false,"date_start":"01.01.1970",
"date_end":"01.01.1970","category":"Kleidung"},"_links":{"self":
[{"href":"http:\/\/localhost:8000\/wp-json\/wp\/v2\/deals\/29"}],
"collection":[{"href":"http:\/\/localhost:8000\/wp-
json\/wp\/v2\/deals"}],"about":[{"href":"http:\/\/localhost:8000\/wp-
json\/wp\/v2\/types\/deals"}],"wp:attachment":
[{"href":"http:\/\/localhost:8000\/wp-json\/wp\/v2\/media?
parent=29"}],"wp:term":[{"taxonomy":"tax_deals","embeddable":true,
"href":"http:\/\/localhost:8000\/wp-json\/wp\/v2\/tax-deals?
post=29"}],"curies":
[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},
I have already tried using
http://localhost:8000/wp-json/wp/v2/deals?search=id
to get the id or something, but response is empty.
Also this didnt work:
http://localhost:8000/wp-json/wp/v2/deals?id=28
Again empty response.
To summarize: I need to filter my custom post type on my custom fields by the "acf" attribute shown in my response json. How does it work?
EDIT: I already installed "WP REST Filter" but still dont know how to do it.
I suggest you to create a new API where you can customize the output. Take advantage of wordpress function register_rest_route() using this you can create an API from CPT and ACF in one ajax url. And you do not need to install anything.
Check how I get my instructor CPT and mycheckbox ACF.
// your ajaxurl will be: http://localhost/yoursite/wp-json/custom/v2/instructor/
add_action( 'rest_api_init', function () {
register_rest_route( 'custom/v2', '/instructor', array(
'methods' => 'GET',
'callback' => 'instructor_json_query',
));
});
// the callback function
function instructor_json_query(){
// args to get the instructor
$args = array(
'post_type' => 'instructor',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'mycheckbox', // your acf key
'compare' => '=',
'value' => '1' // your acf value
)
)
);
$posts = get_posts($args);
// check if $post is empty
if ( empty( $posts ) ) {
return null;
}
// Store data inside $ins_data
$ins_data = array();
$i = 0;
foreach ( $posts as $post ) {
$ins_data[] = array( // you can ad anything here and as many as you want
'id' => $posts[$i]->ID,
'slug' => $posts[$i]->post_name,
'name' => $posts[$i]->post_title,
'imgurl' => get_the_post_thumbnail_url( $posts[$i]->ID, 'medium' ),
);
$i++;
}
// Returned Data
return $ins_data;
}
Then, you can use the link: http://localhost/yoursite/wp-json/custom/v2/instructor/ in your ajax url.

Update User Meta with spaces using REST API - WordPress

I'm trying to update the user meta with spaces registered on my website. I am using register_meta hook to register user meta. And for updating users using WordPress REST API I use wp_remote_post but the problem is when I tried to update a user meta with spaces it will add as array in response then it will add as new user meta.
For example the value of user meta is - community test
Sample Response:
[meta] => Array
(
[agent_community] => Array
(
[0] => community
[1] => test
)
)
Sample Code for registering user meta.
register_meta('user', 'agent_community', array(
"type" => "string",
"show_in_rest" => true
));
Update using wp_remote_post
$update_data = array('email'=> 'test#mail.com', 'meta[agent_community]' => 'community test');
$args = array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'username:password' ),
),
'body' => array_filter($update_data));
$update_url = 'https://test-url.com/wp-json/wp/v2/users/17';
$response = wp_remote_post( $update_url, $args);
Database:
Is there a way that can merge the array on user meta?
implode() might help you. And you can change spaces with HTML entities. Or use function like urledncode() / urlendecode() or something like this.

Custom Post Type & Author not associating, user post count is 0, api doesn't return author in post objects

When Users create custom post types, the author field does not seem to be passed back to WP posts functions.
As the title says, I'm creating a user account programatically, and having that user log-in and write a post of custom post_type = 'job'.
This all LOOKS good in the database - the user, and post are inserted. The post_author is indeed the same as the ID of the user who created it.
But, in the User Accounts panel, that user post count is 0, and the API data object omits the author. I've configured the API for the additional custom post type and the endpoint works to return all post data EXCEPT author.
I've tried creating a post from the CMS with these users as well, and likewise, even if I give them Administrator permissions, they have a 0 post count - the posts are attributed to their author ID. I've also tried to force and update using wp_update_post();
Here's the code to create the user, and then the post:
// Generate the password and create the user
$password = wp_generate_password( 12, false );
$user_id = wp_create_user( $email_address, $password, $email_address );
//login
wp_clear_auth_cookie();
wp_set_current_user ( $user_id );
wp_set_auth_cookie ( $user_id );
// Set the role
$user = new WP_User( $user_id );
$user->set_role( 'subscriber' );
//Ready data for linked post type creation
$new_post = array(
'post_content' => $email_address,
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_id,
'post_title' => $post_name,
'post_name' => $post_name,
'post_type' => $user_type
);
//Create the post
$account_link_post_id = wp_insert_post($new_post);
There was an associated post to this one that shed light on this answer. When registering the post type, I was not setting enough fields in the 'supports' array of the register_post_type. Adding author, whatdayaknow, gives me the datapoint I'm looking for.
register_post_type(self::POST_TYPE,
array(
'labels' => $labels,
'public' => true,
'has_archive' => true,
'description' => __(""),
'supports' => array(
'title', 'author'
),
)
)
NOTE: Post count in the User Accounts page is still 0 - but, the API is returning the data I want/need.

How to create/modfiy WP_Query to search in post title OR custom field?

I need to modify or create a WP_Query that will search for a search term in both the post title OR a custom field (called 'my_field').
I have been reading and trying for hours, but I am right back to this code (below) which, alas, only searches in 'my_field' and does not take the post_title into account.
function my_pre_get_posts_2( $query ) {
if ( is_admin() && $query->is_main_query() && $query->query['post_type'] === 'post' && isset($query->query['s']) ) {
$search_word = $query->query['s'];
$args = array(
//'s' => $search_word, //If I include this line, the WP query seems to AND post_title and my_field. If I comment out this line, the WP query only searches in my_field. (I need WP to OR post_title and my_field.)
'post_type' => 'post',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'my_field',
'value' => $search_word,
'compare' => 'IN'
),
array(
'key' => 'post_title',
'value' => $search_word,
'compare' => 'IN',
)
)
);
//$query = new WP_Query( $args ); //Need to modify the existing WP_Query
$query->init();
$query->parse_query($args);
}
}
add_action( 'pre_get_posts', 'my_pre_get_posts_2' );
The reason I need to do this is because I need to modify the behaviour of the the 'Search Posts' button in the 'All Posts' (admin) page so that whatever the admin user searches for, it will return the posts that have a matching post title OR my_field value.
To do an OR search, I tried merging two separate WP_Query results as shown here - https://wordpress.stackexchange.com/questions/55519/can-i-merge-2-new-wp-queryvariable-s - in guidod's answer. That wasn't a great solution though, and resulted in erratic behaviour.
The correct solution I found was to modify the query using the WP Custom Query as shown in the code (which requires some modifications) here - http://codex.wordpress.org/Custom_Queries .

Drupal FAPI form calls callback twice

First post on stack overflow... so go easy on me!
There doesn't seem to be a suitable solution to the Drupal FAPI multiple callback issue for simple form submissions.
THE PROBLEM: My form, when submitted, adds two entries to the respective database table. Given that there is only one call to add it to the database, I feel it's safe to assume that the query is run twice (hence the dual entries).
The following code may help to provide a basis for a solution. Oh, it's Drupal 7 too, so documentation is still very much D6 centric.
function mymodule_sidebar_form_add_submit(&$form, &$form_state) {
$form_values = $form_state['values'];
$se_title = check_plain(trim($form_values['title']));
$se_link = url(trim($form_values['link']));
$se_content = check_plain(trim($form_values['content']));
$se_image = isset($form_values['image']) ? $form_values['image'] : '';
// The multi-line part below is actually a single line the real code
$query = sprintf("INSERT INTO sidebar_element(title, image_url, content)
VALUES ('%s', '%s', '%s');", $se_title, $se_image, $se_content);
db_query($query);
drupal_set_message(t('Sidebar Element has been added successfully.'));
}
... and my form function contains a submit button:
$form['submit'] = array(
'#value' => t('Add Sidebar'),
'#type' => 'submit',
'#title' => t('Add Sidebar'),
'#submit' => array('mymodule_sidebar_form_add_submit'),
);
I guess the questions I need answered are:
Why is there a double callback in the first place?
Is there a way to identify the first callback?
Thanks in advance to all.
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save')
);
$form['#submit'] = array('my_form_submit');
And replace
// The multi-line part below is actually a single line the real code
$query = sprintf("INSERT INTO sidebar_element(title, image_url, content)
VALUES ('%s', '%s', '%s');", $se_title, $se_image, $se_content);
db_query($query);
with
// The multi-line part below is actually a single line the real code
$query = "INSERT INTO {sidebar_element} (title, image_url, content)
VALUES ('%s', '%s', '%s')";
db_query($query, $se_title, $se_image, $se_content);
For Drupal 7
// Add the buttons.
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
'#type' => 'submit',
'#access' => my_func(),
'#value' => t('Save'),
'#weight' => 100,
'#submit' => array('my_form_submit'),
);
As example read node_form() code
To find out where the second call is coming from, the easiest way is to install devel.module and use ddebug_backtrace() in your submit callback. You might need to disable the HTTP redirecto to see it, too (exit()).
But more importantly, use the API, Luke!
<?php
db_insert('sidebar_element')
->fields(array(
'title' => $se_title,
'image_url' => $se_image,
'content' => $se_content,
))
->execute():
?>
This is how your insert query should look like, what you are doing is insecure!
And for SELECT, use db_query() with named placeholders:
<?php
$result = db_query('SELECT * FROM {sidebar_element} WHERE title = :title', array(':title' => $something));
?>

Resources