How would I go about showing just the first X words of the_content() but only for mobile devices?
You can use this;
<?php
function getFirstXWord($string, $a) {
$temp = explode(" ", $string);
return implode(" ", array_slice($temp, 0, $a, true));
}
echo getFirstXWord("this is a content but do not trust this content", 5);
?>
Here is a working demo: codepad
For mobile detection part, you can use php-mobile-detect class. There is examples in project, I did not stated it here
Two ways immediately come to mind.
One way would be to check the client's user agent with PHP, and then use the_excerpt()
to get an excerpt of the post. You can use the code below to modify the length of the excerpt that you get back.
add_filter('excerpt_length', function() {
return 20;
}, 999);
For more information on the_excerpt()
click here; for more info on add_filter
, click here.
Alternatively, you could use CSS and media queries (more info here) to handle mobile devices. Essentially you'd need two containers that hold your post content:
<div class="post desktop">
Your post content here!
</div>
<div class="post mobile">
Your mobile excerpt...
</div>
And in your CSS:
.mobile {
display: none;
}
@media (max-width: < target device width goes here >) {
.desktop {
display: none;
}
.mobile {
display: block;
}
}
You could add a functions.php
file in your theme folder and do the following
add_filter("the_content", "plugin_myContentFilter");
function plugin_myContentFilter($content)
{
if (wp_is_mobile())
return substr($content, 0, 100); // Show the first 100 characters of content if the user is visiting using a mobile device
else
return $content;
}
Note that I have not tested this but in theory I believe it should work.
Source:
In your content.php
you can change the following line:
<?php if ( is_search()) : ?>
<div class="entry-summary">
<?php the_excerpt(); ?>
</div><!-- .entry-summary -->
to
<?php if ( is_search() || wp_is_mobile()) : ?>
<div class="entry-summary">
<?php the_excerpt(); ?>
</div><!-- .entry-summary -->
You can set your excerpt lenght to what you want it to be