Word count not showing on posts? - php

I thought it might be an issue with a plugin I'm running, but I'm not seeing a word count on any of my posts on WP 4.0. I've deactivated all plugins, and that hasn't fixed me.
Well, not seeing is probably not very accurate - word counts are all 0, even on posts I've written pre-4.0. I'm running roughly latest PHP5.5 and MySQL 5.5 on the server, if that's at all relevant. The database looks fine on the surface, so am I missing something obfious?

You've noted that this is to be used on the frontend of the site, so you can achieve it without the use of a plugin.
Place the following code in your functions.php file:
function word_count() {
$content = get_post_field( 'post_content', $post->ID );
$word_count = str_word_count( strip_tags( $content ) );
return $word_count;
}
You can then use the function word_count() in your theme. word_count() returns the word count of the post, so you'll need to echo it out:
<?php echo word_count(); ?>

Related

Displaying every image from a WordPress post

The goal is to have wordpress spit out or echo all of the images from a custom post format I've created. I'm new to PHP and I am not looking to use any 3rd party plugins, maybe a fix to the code provided below please.
All of the solutions I've came across from here (stackoverflow) or from google does not work or spits out ALL of the images I've ever uploaded from the media library, which I do not want. Most solutions provided are for "display the first image" which I know of and works, but I would like all of the images from a post.
Here's the closest code that sort of worked a couple of times but it deforms my layout, then goes back to displaying one image:
function displayPostImg() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches[0][0];
return $first_img;
}
And the call I use to paste into my custom post php:
<?php echo displayPostImg(); ?>
As stated above, existing solutions do not work. Any help with a clear explination of what I am doing wrong will be a massive help.
EDIT
#corvidism Thanks for the further explanations man. I did have a look in the dev tools and the "return implode" seems to be taking it OUT of the loop, causing the layout issue. Your solution does show the post images/attachments I am after but I can't seem to fix this unfortuntaly. There seems to be this go to solution that's meant to do the same thing. This sadly echoes every image from the media library. Combining your code with this one below has gotten me close but if I come across a solution, I'll post it here for others:
$args = array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_status' =>'any',
'post_parent' => $post->ID );
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo apply_filters( 'the_title' , $attachment->post_title );
the_attachment_link( $attachment->ID , false );
}
}
EDIT #2: Solution
After messing around with various solutions, I found something that works. Try it out:
function grab_those_images( $post ) {
$content_post = $post->post_content;
$search_post = '~src="[^"]*"~';
preg_match_all( $search_post, $content_post, $imgs );
$no_of_pics = count($imgs[0]);
if ( $no_of_pics > 0 ) {
for ( $i=0; $i < $no_of_pics ; $i++ ) {
$string=$imgs[0][$i];
$string=trim( $string );
$length=strlen( $string );
$image_path=substr_replace( substr( $string, 5, $length ),"",-1 );
echo '<img src="';
echo $image_path;
echo '" />';
}
}
}
The function you're using contains buffer manipulation functions (ob_start() and ob_end_clean()), which and are most likely conflicting with something else in your template (probably something that's also using them, usually plugins).
Unless you're also searching for images inserted as post meta (which I assume you're not), you will find all images in a post inside the $post->post_content property. You can use preg_match_all on it to find the images.
You should pass the post content to your function as a parameter instead of accessing the global $post object. This will make things more reliable and easier to debug. (Global objects are generally frowned upon in PHP development, which is something to keep in mind if you plan to use PHP more generally than just for WordPress.)
This is how your function could look:
function getAllImagesInPost($postContent) {
preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $postContent, $matches);
// This regex function searches for <img> tags and uses a capture group
// for the image source url. It will search the whole supplied string,
// in this case post content. It returns results into the $matches variable.
$image_tags = $matches[0];
// This is an array containing all the regex matches.
$image_urls = $matches[1];
// This is an array containing all the capture group matches.
return implode('',$image_tags);
// implode() creates a string from an array of strings/numbers.
}
In your template file, the usage depends on whether or not you're in the loop. In the loop you can work with the $post object and use either $post->post_content or get_the_content() (both will get you the post content as a string):
echo getAllImagesInPost(get_the_content());
Outside of the loop you will first need to get the post (e.g. get_post($somePostID);).
Addition 1:
You must pass a variable to the function, so you can't use WordPress template functions such as the_content(). These echo directly to the page and return true or something else useless (in this case, anyway). General WP rule is that if it starts with the_ it echoes, if it starts get_the_ it returns.
Addition 2:
To display only the images from your post and no other content, you simply don't use any other content template tag in your template file. (E.g. no the_content()).
Addition 3:
I suspect your problem isn't caused by the function itself but by how/where you're calling it. But if this function does cause changes in your layout, it's 99% the regex returning broken HTML (not likely but possible, depending on your input).
The way to debug this is to inspect the page with browser dev tools and look for broken tags or other weirdness. If you see that, you need to find what exactly happens by testing the function on various input. Feed it a hard-coded string, make a test post with just text/image/anything else, until you know what's happening. If you determine that the regex is the culprit, you can try fixing it yourself or search the internet for a better one (no judgement, regex is pain).

Can't Get Wordpress Settings Link To Work

I'm trying to build my first Wordpress plugin and it's giving me a ~LOT~ of grief.
I've got a plugin template I'm using, and I'm following THIS tutorial to turn it into something I can use.
The tutorial says to put a function in [insert plugin name]-admin.php to make 'settings' appear near the plugin on the plugins.php page.
This is what it's supposed to look like:
(source: scotch.io)
The thing is, I have tried inserting the function and I just can't get this 'settings' link to appear.
The code the tutorial says to use is this:
public function add_action_links( $links ) {
$settings_link = array( '' . __('Settings', $this->plugin_name) . '', );
return array_merge( $settings_link, $links );
}
I've tried using this--and similar snippets that I've found on other sites after googling--and none of them work. I know that page= is supposed to link to the page URL, I'm not entirely sure what mine is (is it the plugin slug?). Anyway, I'm currently using the plugin slug after 'page='
If anybody here could help me out with this, it would be greatly appreciated. I know the tutorial I'm using was sloppily written because I have managed to find mistakes in it that were causing errors, and I'm relatively new to PHP and totally new to Wordpress plugins.
Did you also add the beloning add_filter?
Like here:
add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), 'my_plugin_action_links' );
function my_plugin_action_links( $links ) {
$links[] = 'Settings';
$links[] = 'More plugins by WP-Buddy';
return $links;
}
Also see:
https://codex.wordpress.org/Plugin_API/Filter_Reference/plugin_action_links_(plugin_file_name)

Multiple pages with same URL in WordPress

I have a WordPress site that has a standard Page called Places with URL
example.com/places/
And I have several child Pages called by cities
example.com/places/city-1
example.com/places/city-2
Now, I have a custom post type Place that should indicate a single place and should have permalink like
example.com/places/place-1
But then if I go to one of the previous links with city-1, city-2 I get 404 obviously because there is no place with that permalink.
Is there a way for WordPress to drop to previous permalink. So if there is no place with that name, look for a page with it.
You could probably use the the REFERER-value from the PHP server variable $_SERVER, but it´s not very reliable and can be altered.
I am using the plugin "Permalink Finder" in one of the pages I am maintaining and that works quite well for finding changed URL. You could give it a try and see if it works for you, too.
In case somebody ever having a similar problem, it can be done by using verbose page rules. This is an example I found at WordPress Stack Exchange
https://wordpress.stackexchange.com/questions/22438/how-to-make-pages-slug-have-priority-over-any-other-taxonomies-like-custom-post
add_action( 'init', 'wpse16902_init' );
function wpse16902_init() {
$GLOBALS['wp_rewrite']->use_verbose_page_rules = true;
}
add_filter( 'page_rewrite_rules', 'wpse16902_collect_page_rewrite_rules' );
function wpse16902_collect_page_rewrite_rules( $page_rewrite_rules )
{
$GLOBALS['wpse16902_page_rewrite_rules'] = $page_rewrite_rules;
return array();
}
add_filter( 'rewrite_rules_array', 'wspe16902_prepend_page_rewrite_rules' );
function wspe16902_prepend_page_rewrite_rules( $rewrite_rules )
{
return $GLOBALS['wpse16902_page_rewrite_rules'] + $rewrite_rules;
}

wordpress php str_replace function with variables not quite there

I'm pretty new to PHP so perhaps lacking some basics so here goes.
For WordPress I've a function for replacing some text from a TablePress table. The function worked fine when I used code along these lines:
function replace_stuff($text) {
if (is_front_page() || is_page('2611') || is_child('2611')) {
$replace_magic = array(
//text to search => text to replace
'dog' => 'cat',
'mouse' => 'elephant'
);
}
$text = str_replace(array_keys( (array)$replace_magic), $replace_magic, $text);
return $text;
}
add_filter('tablepress_table_output', 'replace_stuff');
So in that example dog would be displayed on the frontend as cat & mouse as elephant.
But now I would like to complicate things & create the strings to replace by querying fields from all posts in a custom post type "drivers".
I have come up with something like this, with the aim of finding any text that matches the post title & replacing with text from a custom field (of all posts from my 'drivers' custom post type), but it doesn't do anything!
function replace_stuff($text) {
if (is_front_page() || is_page('2611') || is_child('2611') || get_post_type() == 'drivers') {
query_posts('post_type=drivers');
if (have_posts()) :
while (have_posts()) : the_post();
$profilenat = get_post_meta($post->ID, 'driver_nationality', true);
$profiletitle = get_the_title();
$replace_magic = array(
//text to search => text to replace
$profiletitle => $profilenat
);
endwhile;
endif;
}
$text = str_replace(array_keys( (array)$replace_magic), $replace_magic, $text);
return $text;
}
add_filter('tablepress_table_output', 'replace_stuff');
Could anyone advise me please?
Many thanks.
Firstly I think you need to replace
$replace_magic = array(
with
$replace_magic[$profiletitle] = $profilenat
Currently, if everything else works, then for every driver you are completely replacing the contents of $replace_magic with a new array, which just has that driver's details. Instead you want to add a new item to the existing array.
Going further, with this sort of problem it can be really useful to do some quick debugging to help you narrow down where the problem might be. So here it would be useful to know if the problem is really with your str_replace, or if it's actually with the code above it.
Debugging in Wordpress is worth a read, and having done that you can use error_log to output some details to debug.log inside your wp-content directory.
Before your str_replace, doing
error_log(print_r($replace_magic));
Would tell you if your query loop has worked as you intended or not.
If it hasn't, you might then put a log statement inside the loop. This will tell you if the loop contents are being executed at all (in which case the problem is with your code inside the loop), or not (in which case the problem may be with your query).
Additionally, if you haven't already I would recommend checking the WordPress Codex on query_posts. query_posts manipulates the main Wordpress query, and may give you some really unexpected results used inside a filter like this. At least consider WP_Query - and check the note about wp_reset_posts.
Hope that helps - apologies if some of it is stuff you already considered, but as you mentioned you're quite new to PHP I hope it's useful.

Wordpress keeps "cleaning" my post format html

So here i find myself, again, struggling with wordpress wysiwyg editor.
a client of mine requested to migrate his website to WP. No probs, a breeze :).
Really was easy, migrated from one DB structure to the other, and everything went OK.
Now I have a problem. The old site, used an editor that added <br> and <p> tags to the content in order to format it (sounds legit to me). But wordpress will not allow these tags. whenever the client tries to edit a post, WP removes all the HTML tags it considers "illegal".
So I went on the search. First I tried to install some recommended plugins I found for this problem (such as this one). Didn't work at all for me (for some others it did i believe)...
Then I found a post that told me to add a function to the function.php file which will remove the filters :
function mod_mce($initArray) {
$initArray['verify_html'] = false;
return $initArray;
}
add_filter('tiny_mce_before_init', 'mod_mce');
and also this:
function my_tinymce( $init ) {
$ext = 'div[id|name|class|style]';
if ( isset( $init['extended_valid_elements'] ) ) {
$init['extended_valid_elements'] .= ',' . $ext;
} else {
$init['extended_valid_elements'] = $ext;
}
return $init;
}
add_filter( 'tiny_mce_before_init', 'my_tinymce' );
functions from this thread.
Nope, didn't work also...
Someone - any idea? It seems so silly, but there is so much debate around this subject...
Thanks
You may try this to remove filters that wpautop uses to filter content and excerpt, just put these in your funcions.php file
remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );
Reference: WordPess wpautop
To allow older content with p and br to load in tinyMCE
function my_tinymce_config( $init ) {
$init['remove_linebreaks'] = false;
$init['convert_newlines_to_brs'] = true;
$init['remove_redundant_brs'] = false;
return $init;
}
add_filter('tiny_mce_before_init', 'my_tinymce_config');
Reference: tinyMCE Configuration look at Cleanup/Output and try playing with these.
Another way could be helpful Reference
tinyMCE.init({
...
verify_html : false
});

Categories