so currently i'm using pods to create some individual pages for a log, filled with custom stuff.
now i want to use the comments-system for each of this pages e.g.:
mydomain.com/podpages/page1
mydomain.com/podpages/page2
mydomain.com/podpages/page3
this are not pages created with wordpress so simply adding <?php comments_template(); ?> is not working.
any ideas how to solve this problem?
thanks in advance
please leave a comment if something is unclear :)
When a comment is stored in the WordPress database, the ID of the post (or page) the comment relates to is also stored.
Trouble is, you're trying to save comments using WordPress, but for a page that it doesn't actually know about.
So, how about we create a WordPress page for each real page, but merely as a representation, so that your real pages and WordPress have a common ground for working with each other.
So, the plan here is to;
Load WordPress in the background on each of the 'real' pages.
See if a WordPress page representation already exists for the 'real' page
If it doesn't, create it, then and there
Trick WordPress into thinking we're actually viewing the representation
Carry on using all of WP's functions and 'template tags' as you would normally
This code should be somewhere at the beginning of the template file used to render your 'real' pages;
include ('../path/to/wp-load.php');
// remove query string from request
$request = preg_replace('#\?.*$#', '', $_SERVER['REQUEST_URI']);
// try and get the page name from the URI
preg_match('#podpages/([a-z0-9_-]+)#', $matches);
if ($matches && isset($matches[1])) {
$pagename = $matches[1];
// try and find the WP representation page
$query = new WP_Query(array('pagename' => $pagename));
if (!$query->have_posts()) {
// no WP page exists yet, so create one
$id = wp_insert_post(array(
'post_title' => $pagename,
'post_type' => 'page',
'post_status' => 'publish',
'post_name' => $pagename
));
if (!$id)
do_something(); // something went wrong
}
// this sets up the main WordPress query
// from now on, WordPress thinks you're viewing the representation page
}
UPDATE
I can't believe I was this stupid. Below should replace current code inside outer if;
// try and find the WP representation page - post_type IS required
$query = new WP_Query(array('name' => $pagename, 'post_type' => 'page'));
if (!$query->have_posts()) {
// no WP page exists yet, so create one
$id = wp_insert_post(array(
'post_title' => $pagename,
'post_type' => 'page',
'post_status' => 'publish',
'post_name' => $pagename,
'post_author' => 1, // failsafe
'post_content' => 'wp_insert_post needs content to complete'
));
}
// this sets up the main WordPress query
// from now on, WordPress thinks you're viewing the representation page
// post_type is a must!
wp(array('name' => $pagename, 'post_type' => 'page'));
// set up post
the_post();
P.S I think using the query_var name over pagename is better suited - it queries the slug, rather than the slug 'path'.
You'll also need to either place an input inside the form with name redirect_to and a value of the URL you'd like to redirect to, or, filter the redirect with a function hooked onto comment_post_redirect, returning the correct URL.
add
require('/path/to/wp-blog-header.php');
to include the wp files. this should give you all the functions/data you need.
Can you create pages in wordpress which display your log data? You might need a new template for this. WordPress will then have something to connect the comments to.
Do you need to use WordPress for this? If not, maybe something in this SO question helps: Unobtrusive, self-hosted comments function to put onto existing web pages
Just supply the wordpress-comment-part with a new ID - start with something your usual posts will never reach (100.000+ is your pages i.e.)
I don't know exactly if in wordpress it's a function (saveComment i.e.), but if it is so, just use it in your page with he custom ID.
You will nevertheless have to insert the Comments-form yourself.
And don't forget to modify the query that gets the news-entires that IDs over 100.000 are not entries.
Or you can write your own template that displays the standard-Worpress-stuff with IDs < 100.000, or else your pages.
Summed up, it should not be very difficult.
p.s.: If you just want to use the wordpress-login, then use any comment-system or make your own (it's an 1hour-thing) and authenticate / use the worpress-session.
Related
I have a need to change a plugin that creates/edits entries to the wp_posts table. Currently, it is lacking in that it cannot target some specific fields. I am endeavoring to edit the plugin so I can change these fields as well with the plugin. Specifics below.
How would I generally target this table then create/edit entries?
I have in mind something like this, which was copied from here.:
$my_post = array(
'post_title' => '#Enter the title#',
'post_content' => '#Enter the Content#',
'post_status' => 'publish',
'post_author' => 1
);
wp_insert_post( $my_post );
I assume this is possible because the plugin I'm hoping to change already makes changes to the wp_posts table. How do I do this? I have programming experience in C#, but my PHP and WP knowledge is severely lacking. I assume there's a few WordPress key functions that I'm looking for, but I simply don't know what they are or how to find them (I might be searching for the wrong terms). wp_insert_post() looks very promising, but the documentation seems to imply that it won't work for my specific needs.
Specifics
I'm using a great plugin called Really Simple CSV importer (RSC), which allows you to create/update posts with a csv. It seems to be able to target nearly every field (e.g. post_title, post_id, post_parent, post_content, _wp_page_template, etc.). This is quite a boon if you have to create hundreds of pages regularly (which I do).
The problem is that it won't target two specific fields, which are titled group_access and tag_list. I put those fields as columns in my csv, but they are not added to the mySQL database, and thus are not changed on the site. I believe these fields are specific to a plugin called iMember360, which is a plugin that ties into an InfusionSoft account.
Naturally, I've tried contacting RSC support, but have received no replies at all. I've spoken to iMember360 support at length, and the best they can give me without doing the work themselves is that they use the action hook import_end to make changes to the table, so if RSC is not using it, then it won't affect those fields. They also say that iMember360 has an import/export function, but it is only for the plugin's specific features, and ties in with the WordPress XML import/export feature. Clearly, this RSC plugin does not do that.
Regardless of these limitations, it seems to me like if the field exists in the table, then you should be able to edit it, so I tend to think that the RSC plugin is simply lacking in this functionality, probably only targeting WP default fields only.
What I've tried:
I have tried editing the plugin PHP directly, with the assumption that the plugin simply does not have an entry for the group_access and tag_list fields.
One of the PHP files contained:
// (string, comma separated) name of post tags
$post_tags = $h->get_data($this,$data,'post_tags');
if ($post_tags) {
$post['post_tags'] = $post_tags;
}
I simply copied and pasted it right above it and changed post_tags to group_access. It didn't work.
I also found, and added to:
$attachment = array(
'post_mime_type' => $mime_type ,
'post_parent' => $this->postid ,
'post_author' => $this->post->post_author ,
'post_title' => $title ,
'post_content' => $content ,
'post_excerpt' => $excerpt ,
'post_status' => 'inherit',
'menu_order' => $this->media_count + 1,
////////// added
'group_access' => $group_access ,
'tag_list' => $tag_list ,
//////
);
That didn't do anything either.
There are two ways to edit the wp_posts table that I know of. The first is with the wp_update_post() and wp_insert_post() functions. These are typical WP functions that are used like any others. You just have to pass the correct parameters. For example:
$my_post = array(
'ID' => $updatePostID, // User defined variable; the post id you want to update.
'post_title' => 'Update Title',
'post_content' => 'Update Content',
);
// Update the post into the database
$post_id = wp_update_post( $my_post, true ); // Returns 0 if no error; returns post id if there was an error.
// Check if table was updated without error. For debugging. Remove from your code if it all works, before publishing.
if (is_wp_error($post_id)) {
$errors = $post_id->get_error_messages();
foreach ($errors as $error) {
echo $error;
}
}
Simply pass an array with the predefined field names to the functions and they will then run correctly. The update function is for updates, naturally, and the insert function creates new table entries (rows). There is a limitation, however. These two functions will only operate on the WP predefined fields. So, if your table contains some custom fields, then you will have to use the $wpdb class.
The other way to update your mySQL tables from WordPress is to use the $wpdb class directly. This class is far more expansive than the wp_update_post() and wp_insert_post() functions. The first difference is that it can edit many other mySQL tables, not just the wp_posts table. It can also edit non-WP fields. For example:
global $wpdb; // This calls the use of the class. I actually do not think this is necessary, but I do it anyway.
$dbresult = $wpdb->update($wpdb->posts, // Returns 0 if no errors. Post ID if errors occurred.
// Notice posts instead of wp-posts. Prefixes are not necessary with this class.
['post_title' => 'Update Title',
'post_content' => 'Update Content',
'custom_field' => $customField, ], // User defined table column and variable.
['ID' => $updatePostID, ]); // User defined variable; the post id.
if (false === $dbresult) {
echo 'An error occurred while updating...';
$errors = $post_id->get_error_messages();
}
I'm not very familiar with either of these options, but there seems to a massive difference in the width of functionality, so there may be considerations you should take before using one over the other. I've asked a question to that end: https://wordpress.stackexchange.com/q/259043/38365 One reply says:
Downsides of $wpdb are that you do need to know SQL and you need to be conscious of normal data sanitization and when to use prepare() and what functions already prepare your statement which are hardly downsides at all. The $wpdb Class is by nature more powerful than any of the default WordPress functions because you have access to all the data, custom or not, assuming you know the proper SQL to get, modify, or remove it.
TL;DR $wpdb is more powerful but less friendly and forgiving.
That makes sense to me. Basically, don't fiddle with $wpdb unless you know what you are doing or absolutely have to.
I have installed the Wordpress API onto on of our company websites so that we can retrieve data from it to display on a new company website. With regards to grabbing and displaying the initial data all works fine (posts from a specific category from the original website onto a specific page on the new website).
This is for a events that are input onto a 'whats on' page on the existing website that take place at a bar/restaurant. The new site is purely dedicated to the events and to save having to add/amend the events on both sites we thought it best to use the API.
To retrieve the full listing of events (which works) I use:
$response = wp_remote_get( 'http://restuarantdomain.com/wp-json/wp/v2/posts?filter[category_name]=live-events&per_page=50' );
I also know that to display an individual post I need to use:
$response = wp_remote_get( 'http://restaurantdomain.com/wp-json/wp/v2/posts?filter[name]=event_name );
What I can't work out how to do is create a 'friendly' url on the new site that will then go to a page that calls the function to get the individual post details.
For example I want the url http://eventdomain.com/whats-on/event-name (in the list of event posts grabbed through the 1st API call above) to go to the page What's On and on that page use the event-name from the url as the parameter in the 2nd API call above. But Wordpress just looks for the category and post name due to the format of the url which don't exist so I just get a 404.
What am I missing?
You must create your custom Endpoints.
for instance, if you want to filter all posts within a particular category you should do this
function my_cat_func( $data ) {
$posts = get_posts( array(
'cat' => $data['id'],
) );
if ( empty( $posts ) ) {
return null;
}
return $posts[0]->post_title;
}
then you must add an action to register your endpoint call
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v2', '/categoy/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_cat_func',
) );
} );
then you will get something like this
http://example.com/wp-json/myplugin/v2/categoy/(?P<id>\d+)
for more information and better understanding, I suggest you reading this reference:
http://v2.wp-api.org/extending/adding/
This article also can give you more example: https://webdevstudios.com/2015/07/09/creating-simple-json-endpoint-wordpress/
and
https://deliciousbrains.com/wp-rest-api-customizing-endpoints-adding-new-ones/
Note: I wrote this code on the fly, that should need more efforts to work.
I'm writing some code that will read a csv with information about real estate listings, and either create a post for that listing or update the current post. The title of each listing is the address, so if it detects a post with that address already made, I want it to update the current post. The posts are of a custom type "listing" with custom fields such as "_listing_address" (also the post_title) and "_listing_price", etc. Here is the part of the code that initializes the array for a new post or with data to update the new post:
$new_post = array(
'post_title' => convert_chars($data['csv_post_title']),
'post_content' => wpautop(convert_chars($data['csv_post_post'])),
'post_status' => $opt_draft,
'post_type' => $type,
'post_date' => $this->parse_date($data['csv_post_date']),
'post_excerpt' => convert_chars($data['csv_post_excerpt']),
'post_name' => $data['csv_post_slug'],
'post_author' => $this->get_auth_id($data['csv_post_author']),
'tax_input' => $this->get_taxonomies($data),
'post_parent' => $data['csv_post_parent'],
);
And here is the code that either creates a new post or (should) update an existing post:
if (!get_page_by_title( $new_post['post_title'], 'OBJECT', 'listing')) {
$id = wp_insert_post($new_post);
} else {
$old_post = get_page_by_title( $new_post['post_title'], 'OBJECT', 'listing' );
$new_post['ID'] = $old_post->ID;
$id = wp_update_post($new_post);
}
I can successfully create new posts with the code that I have, and it also successfully checks if another post has the same title, since it doesn't create duplicate posts. However, it doesn't actually update the posts. So if on my csv file I change the price of one of the listings from $29,900 to $30,000, when I re-upload the csv, it won't create a new post since the address didn't change, but it won't change price of the current post. I'm guessing it's a problem with the post ID's, but anything I've tried hasn't worked. Any help would be greatly appreciated.
Other relevant information:
I'm using the CSV Importer plugin for Wordpress, which I modified with the above code to check for duplicate posts and update them. I'm also using the Genesis framework and the Agentpress theme, which creates the listing custom type.
I figured it out. The problem was that the code I had above creating an array didn't deal with any custom fields - those were handled by another function called later on, which used the create_post_meta() function for Wordpress to create the custom fields. Obviously this was a problem for me since I was trying to update post meta fields that had already been created. All I had to do was switch this to update_post_meta(), which both updates already created post meta or creates a new one if it hasn't. Hopefully this helps anyone who is using CSV Importer or has made their own CSV upload plugin and is struggling to both create and update posts from a CSV file.
I have a strange problem when using the wp_update_nav_menu_item function in a multisite installation.
It normally works when I execute this from within wp-admin. However, now I've been tasked with writing a handler script to auto-create a site, add a number of default pages, add a menu and populate the menu with those pages.
Here is the code in question:
$miid = wp_update_nav_menu_item($menu_id, 0, array(
'menu-item-title' => $post['post_title'],
'menu-item-object' => 'page',
'menu-item-object-id' => $pid,
'menu-item-type' => 'post_type',
'menu-item-status' => 'publish',
'menu-item-parent-id' => $navParentID,
'menu-item-position' => $post['menu_order']));
I've ensured that all of the values passed in to the function are correct and match with those which would be passed in when I call this function from within wp-admin dashboard.
The blog gets created successfully, as do the default pages, and the menu. When this executes it does return a $menu_item_db_id value indicating it worked successfully but nothing has actually been added to the menu and calling something like print_r(wp_get_nav_menu_object($menu_id)); returns nothing.
When I call the same exact function with the same exact inputs from a page within wp-admin everything works fine.
I've considered that perhaps the current blog context was not set correctly and have used this snippet to validate that I'm in the correct blog:
//Ensure we're updating the correct blog
$blogid = get_current_blog_id();
switch_to_blog($blogid);
echo get_current_blog_id()."<br/>";
Has anyone else encountered this issue?
I've had exactly the same problem..
The solution was to create item and menu relationship for each item :
wp_set_object_terms($item_id, $menu_id, 'nav_menu');
For some reason it was not created in wp_update_nav_menu_item
I'm currently working on a website for a DJ friend of mine who uploads his mixes to Soundcloud to share, he will also be using his website to post his mixes (via Soundcloud) and to post events.
To handle the events side of things, rather than using a custom post type, I simply added my own meta fields to the standard post screen, and set-up the posts to display the event info if it is set, and display the posts normally if not. Full code, relevant part:
global $wp_query;
$postid = $wp_query->post->ID;
$event_venue = get_post_meta($postid, 'event_venue', true);
In addition to this, to handle his mixes, I have set up a custom post type (generally to make it easier for him to distinguish, as he's not terribly techsavvy outside of a mixer and turntables) and custom meta fields to allow him to add where the mix was recorded (venue-wise) and his soundcloud URL to the mix (which is used to automatically embed the mix in the post, rather than using a plugin). I have created a custom loop and single-mixes.php page to handle the display of the data, which is essentially the original loop (renamed to loop-mixes.php so I know what's what) but includes a file mix_data.php. Full code, relevant part:
global $wp_query;
$postid = $wp_query->post->ID;
$mix_venue = get_post_meta($postid, 'mix_venue', true);
Now, my question. I would like, in the single post page, to compare the data held in $mix_venue with every other post that has $event_venue set, and display those posts which are a match (i.e, so if a user is viewing a mix, they can then see any upcoming events (and, indeed, any past events) held in the venue in which it was recorded).
But, I'm teaching myself WordPress as I go, and I'm really not entirely sure where to begin with this one.
I see that you solved it, but I'll suggest a re-usable approach.
In your theme's functions.php put this function (full arguments list for get_posts()):
function print_event_venues( $mix_venue )
{
$args = array(
'numberposts' => -1,
'post_type' => 'post',
'post_status' => 'publish',
'meta_key' => 'event_venue',
'meta_value' => $mix_venue
);
$posts = get_posts( $args );
// DO NOTHING
if( !$posts )
return;
foreach( $posts as $post )
{
// DO YOUR HTML
echo $post->post_title;
}
}
Then, in any template, simply call it: print_event_venues( $the_mix_venue );.
Useful info: When should you use WP_Query vs query_posts() vs get_posts()?.