I have a code that shows in-article ads after a specified amount of words, the thing is:
If I write a very long article, the ad will be lost due to text length, so there will be only text showing. What I need to do is to create 1 or 2 ads and make it/them repeat indefinitely every 4 paragraphs and 250 words (just an example), based on article length.
HERE'S AN EXAMPLE:
This blog has the very same thing that I'm trying to achieve. As you scroll the article, you'll see that more and more ads will be loaded between the article paragraphs.
THIS IS MY CURRENT CODE:
// Insert ads after a number of words and after the </p> closing tag.
// https://stackoverflow.com/questions/42801541/insert-text-in-content-after-300-words-but-after-closing-tag-of-a-paragraph
function anunciamentosegundo($content) {
$ad_code = '<script type="application/javascript">Adsense code goes here</script>';
// only inject google ads if post is longer than 800 characters
$enable_length1 = 1800;
// Insert at the end of the paragraph every 200 words
$after_word1 = 400;
// Maximum of 2 ads
$max_ads = 2;
if (strlen($content) > $enable_length1) {
$len = strlen($content);
$i=0;
// Keep adding untill end of content or $max_ads number of ads has ben inserted
while($i<$len && $max_ads-->0) {
// Work our way untill the apropriate length
$word_cout = 0;
$in_tag = false;
while(++$i < $len && $word_cout < $after_word1) {
if(!$in_tag && ctype_space($content[$i])) {
// Whitespace
$word_cout++;
}
else if(!$in_tag && $content[$i] == '<') {
// Begin tag
$in_tag = true;
$word_cout++;
}
else if($in_tag && $content[$i] == '>') {
// End tag
$in_tag = false;
}
}
// Find the next '</p>'
$i = strpos($content, "</p>", $i);
if($i === false) {
// No more paragraph endings
break;
}
else {
// Add the length of </p>
$i += 4;
// Get ad as string
ob_start();
echo $ad_code ; //would normally get printed to the screen/output to browser
$ad = ob_get_contents();
ob_end_clean();
$content = substr($content, 0, $i) . $ad . substr($content, $i);
// Set the correct i
$i+= strlen($ad);
}
}
}
return $content;
}
add_filter( 'the_content', 'anunciamentosegundo' );
Currently I can show ads after an amount of words and paragraphs, but not every x amount words and paragraphs. What should I do?
Related
My function gets all the facebook description text from our string $FBdescription. This preg_replace does everything I need except when it finds a url like www.myurl.com in the description it places that in the href= and because it does not contain the http:// at the begining it of course causes problems when you click the link. How can this be adjusted to append the http:// if it's not there.
function fts_facebook_tag_filter($FBdescription)
//Converts URLs to Links in our Description Text
$FBdescription = preg_replace('#(?!(?!.*?<a)[^<]*<\/a>)(?:(?:https?|ftp|file)://|www\.|ftp\.)[-A-Z0-9+&#/%=~_|$?!:,.]*[A-Z0-9+&#/%=~_|$]#i', '\0', $FBdescription);
return $FBdescription;
}
Not best but working solution: (prepends http:// if missing, inside href attribute only)
$FBdescription = 'BZRK Records and BZRK Black label Artists playing here More info : www.bzrk.agency https://www.facebook.com/daphne.merks/posts/988562257858538';
//Converts URLs to Links
$FBdescription = preg_replace('#(?!(?!.*?<a)[^<]*<\/a>)(?:(?:https?|ftp|file)://|www\.|ftp\.)[-A-Z0-9+&#/%=~_|$?!:,.]*[A-Z0-9+&#/%=~_|$]#i', '\0', $FBdescription);
$splitano = explode("www", $FBdescription);
$count = count($splitano);
$returnValue = "";
for($i=0; $i<$count; $i++) {
if (substr($splitano[$i], -6, 5) == "href=") {
$returnValue .= $splitano[$i] . "http://www";
}
else if($i < $count - 1){
$returnValue .= $splitano[$i] . "www";
}
else {
$returnValue .= $splitano[$i];
}
}
echo $returnValue;
I wrote a program that creates a puzzle based on user's inputs. There is a html form that accepts the user's words and posts them to the php program. Then the php program creates the puzzle and prints it.
There is a live demo here. You can type you own words.
It looks good but when I run it in my local server with php error prompt turned on, I see the error msg saying Undefined offset: 10 at line 147 and 148. The error is generated from the php code line starting from if ($board[$curr_row][$curr_col] == '.'... You can use Ctrl+F to find the code. I don't understand how could I get 10 in $curr_col or $curr_row since the loop should stop after they reach 9.
Please help me understand how could the loop run after they have reached 10, thanks a lot!
The zipped version of the program is here.
Here is the code of the php:
<html>
<body>
<?php
/* word Find
Generates a word search puzzle based on a word list entered by user.
User can also specify the size of the puzzle and print out
an answer key if desired
*/
//If there is no data from the form, prompt the user to go back
if (!filter_has_var(INPUT_POST, "puzzle_name")) {
print <<<MUL_LINE
<!DOCTYPE html>
<html >
<head>
<title>Oops!</title>
</head>
<body>
<p>This page should not be called directly, please visit
the puzzle form to continue.</p>
</body>
</html>
MUL_LINE;
} else {
$boardData = array("name" => filter_input(INPUT_POST, "puzzle_name"), "width" => filter_input(INPUT_POST, "grid_width"), "height" => filter_input(INPUT_POST, "grid_height"));
if (parseList() == TRUE) {//parse the word list in textarea to an array of words
//keep trying to fill the board untill a valid puzzle is made
do {
clearBoard();
//reset the board
$pass = fillBoard();
} while($pass == FALSE);
printBoard();
//if the board if successfully filled, print the puzzle
}
}//end word list exists if
//parse the word list in textarea to an array of words
function parseList() {
//get word list, creates array of words from it
//or return false if impossible
global $word, $wordList, $boardData;
$wordList = filter_input(INPUT_POST, "wordList");
$itWorked = TRUE;
//convert word list entirely to upper case
$wordList = strtoupper($wordList);
//split word list into array
$word = explode("\n", $wordList);
//an array of words
foreach ($word as $key => $currentWord) {
//trim all the beginning and trailer spaces
$currentWord = rtrim(ltrim($currentWord));
//stop if any words are too long to fit in puzzle
if ((strlen($currentWord) > $boardData["width"]) && (strlen($currentWord) > $boardData["height"])) {
print "$currentWord is too long for puzzle";
$itWorked = FALSE;
}//end if
$word[$key] = $currentWord;
}//end foreach
return $itWorked;
}//end parseList
//reset the board by filling each cell with "."
function clearBoard() {
//initialize board with a . in each cell
global $board, $boardData;
for ($row = 0; $row < $boardData["height"]; $row++) {
for ($col = 0; $col < $boardData["width"]; $col++) {
$board[$row][$col] = ".";
}//end col for loop
}//end row for loop
}//end clearBoard
//fill the board
function fillBoard() {
global $word;
$pass = FALSE;
//control the loop of filling words, false will stop the loop
//control the loop, if all the words are filled, the counter will be as equal to the number
//of elements in array $words, thus the loop stops successfully
$counter = 0;
do {
$pass = fillWord($word[$counter]);
//if a word is filled, $pass is set to true
$counter++;
}
//if a word can't be filled, pass==FALSE and loop stops
//or if all words are through, loop stops
while($pass==TRUE && $counter<count($word));
//return TRUE if all filled successfully, FALSE if not
if ($pass == TRUE && $counter == count($word)) {
return TRUE;
} else {
return FALSE;
}
}
//function used to fill a single word
function fillWord($single_word) {
global $board, $boardData;
//the direction of how the word will be filled, 50% chance to be H, and 50% chance to be V
$dir = (rand(0, 1) == 0 ? "H" : "V");
//H(horizontal) means fill the word from left to right
//V(vertical) means fill the word from up to down
//loop control. if a letter is not filled, $pass is set to false and loop stops
$pass = TRUE;
//loop control. if all letters are filled successfully, loop stops too.
$counter = 0;
//decide the cell to fill the first word. the cell is located at $board[$curr_row][$curr_col]
if ($dir == "H") {//if the word will be fileld from left to right
$curr_row = rand(0, $boardData["height"] - 1);
//pick up a random row of the 10 rows ( rand(0,9) )
$curr_col = rand(0, ($boardData["width"] - ( strlen($single_word - 1)) - 1));
//pick up a random column of fillable columns
//if the word is "banana" and the board's width
//is 10, the starting column can only be rand(0, 4)
} else if ($dir == "V") {//if the word will be fileld from up to down
$curr_row = rand(0, ($boardData["height"] - ( strlen($single_word - 1)) - 1));
$curr_col = rand(0, $boardData["width"] - 1);
} else {
print "invalid direction";
}
//the loop that keeps trying to fill letters of the word
while ($pass && ($counter < strlen($single_word))) {//while the $pass is true AND there are still letters
//to fill, keep the loop going
//the next line and the line after generate the msg "Undefined offset: 10",
//$curr_row and $curr_col should never be 10 because the loop should be stopped
//if the last letter of the word is filled
if ($board[$curr_row][$curr_col] == '.' || //if the cell is not filled, reset fillboard() to "."
$board[$curr_row][$curr_col] == substr($single_word, $counter, 1))//or it has already been filled with the same letter
{
$board[$curr_row][$curr_col] = substr($single_word, $counter, 1);
// write/fill the letter in the cell
$counter++;
if ($dir == "H") {
$curr_col++;
//next column, move to the next right cell
} else if ($dir == "V") {
$curr_row++;
//next row, move to the next lower cell
} else {
print "\nHuge direction error!";
}
} else {
$pass = FALSE;
// failed to fill a letter, stop the loop
}
}
//if all the letters are filled successfully, the single word is filled successfully
//return true, let $fillBoard go filling next single word
if ($pass && ($counter == strlen($single_word))) {
/* for debug purpose
print "<hr />";print "<p>TRUE</p>";print "<hr />";
print $single_word;
print $curr_row . "," . $curr_col . "<br />";
print "<hr />";*/
return TRUE;
} else {
//failed to fill the word, reset the board and start all over again
return FALSE;
}
}//end function fillWord
//print the successful filled puzzle
function printBoard() {
global $board;
print <<<MULLINE
<style type="text/css">
table, td{
border: 1px solid black;
}
</style>
MULLINE;
print '<table >';
foreach ($board as $row) {
print '<tr>';
foreach ($row as $cell) {
print '<td>';
print $cell;
print '</td>';
}
print("<br />");
print '</tr>';
}
print "</table>";
}
?>
</body>
</html>
I don't think the following fragment of code is right.
strlen($single_word - 1)
located in the lines:
$curr_col = rand(0, ($boardData["width"] - ( strlen($single_word - 1)) - 1));
and
$curr_row = rand(0, ($boardData["height"] - ( strlen($single_word - 1)) - 1));
It will convert the word to an integer. Subtract one from that number. Then convert that back to a string and take the length. So you have a rubbish value for the length.
I'm using a function to decide what the length of my articles are (below). The issue is that on my index page, the_content seems to be 'split up' by my <!-- more --> tags.
For example, my article is 3000 characters long, but my index page only shows 500 characters before the 'Read More' link appears. My function uses the 500 characters as the_content instead of the actual 3000 characters. The length is shown as Short, even though the full articles is considered Long.
However on the full article page, where all 3000 characters are shown, the function works fine.
Now my question is: is there an alternative for the_content that ALWAYS uses the full article instead of what's currently shown on the page?
function wcount(){
ob_start();
the_content();
$content = ob_get_clean();
$length = strlen($content);
if ($length > 2000) {
return 'Long';
} else if ($length > 1000) {
return 'Medium';
} else if ($length < 1000) {
return 'Short';
}
}
Try this:
function wcount($post) {
$length = strlen($post->post_content);
if ($length > 2000) {
return 'Long';
} else if ($length > 1000) {
return 'Medium';
} else if ($length < 1000) {
return 'Short';
}
}
Then call wcount() from within the post loop with something like echo wcount($post);
Try
global $more;
$more = 0;
the_content();
Basically I want to echo only summary of my blog post on a certain page by making a function() that must limit the number of counts of words as specified there.
function sumarize($your_string){
$count++;
$maximum = 10;
foreach(explode("\n", $your_string) as $line){
$count++;
echo $line."\n";
if ($count == $maximum) break;
}
}
Lets say your table (named main) looks like that.
id | blogpost
1 sample1
2 sample2
...
At first you need to connect to db
$db=NEW MYSQLI('localhost', 'username', 'pass', 'dbname') or die ($db->error);
Then write following piece of code
function sumarize($your_string){
$count++;
$maximum = 10;
foreach(explode("\n", $your_string) as $line){
$count++;
echo $line."\n";
if ($count == $maximum) break;
}
}
$result=$db->query("SELECT `id`, `blogpost` FROM `main`");
while($row->fetch_object()){
echo sumarize($row->blogpost);
}
This is how to get work genesis φ's solution
this one takes into account numbers of character whilst ending at the last word without cutting out a character
use
select .... SUBSTR(body,1,300) .....
later you can use this function in php to cut the string at the last space or period so you wont get a half cut word in the end. The second parameter is the number of characters you want.
function shorten_string($string, $characters)
{
$shortened_string = "";
$smaller_string = substr($string, 0, $characters);
$pos_of_last_space = strrpos($smaller_string, " ");
$pos_of_last_break = strrpos($smaller_string, " ");
if (strlen($string) <= $characters) {
$shortened_string = $string;
} elseif (!$pos_of_last_space && !$pos_of_last_break) {
$shortened_string = $smaller_string;
} else {
$break_at = 0;
if ($pos_of_last_space > $pos_of_last_break) {
$break_at = $pos_of_last_space;
} else {
$break_at = $pos_of_last_break;
}
$shortened_string = substr($smaller_string, 0, $break_at);
}
}
NOTE: takes care of spaces put in html with 'nbsp'
Save the summary and body of your blog posts in different columns.
My function searches google for the specific keyword and then checks for the site and then returns the what position it is on google (its for my seo dashboard) but it always return's 0, hopefully some fresh eyes can find the faults
<?php
function GoogleSerp($searchquery, $searchurl){
if(!empty($searchquery) && !empty($searchurl))
{
$query = str_replace(" ","+",$searchquery);
$query = str_replace("%26","&",$query);
// How many results to search through.
$total_to_search = 50;
// The number of hits per page.
$hits_per_page = 10;
// Obviously, the total pages / queries we will be doing is
// $total_to_search / $hits_per_page
// This will be our rank
$position = 0;
// This is the rank minus the duplicates
$real_position = 0;
$found = NULL;
$lastURL = NULL;
for($i=0;$i<$total_to_search && empty($found);$i+=$hits_per_page)
{
// Open the search page.
// We are filling in certain variables -
// $query,$hits_per_page and $start.
// $filename = "http://www.google.co.uk/xhtml?q=$query&start=$i&sa=N";
$filename = "http://www.google.co.uk/m?q=$query&num=$hits_per_page&filter=0&start=$i&sa=N";
$file = fopen($filename, "r");
if (!$file)
{
return "error";
}
else
{
// Now load the file into a variable line at a time
while (!feof($file))
{
$var = fgets($file, 1024);
// Try and find the font tag google uses to show the site URL
if(eregi("<span class=\"c\">(.*)</span>",$var,$out))
{
// If we find it take out any <B> </B> tags - google does
// highlight search terms within URLS
$out[1] = strtolower(strip_tags($out[1]));
// Get the domain name by looking for the first /
$x = strpos($out[1],"/");
// and get the URL
$url = substr($out[1],0,$x);
$url = str_replace("/","",$url);
$position++;
// If you want to see the hits, set $trace to something
// if($trace)return($url."<br>");
// If the last result process is the same as this one, it
// is a nest or internal domain result, so don't count it
// on $real_position
if(strcmp($lastURL,$url)<>0)$real_position++;
$lastURL = $url;
// Else if the sites match we have found it!!!
if(strcmp($searchurl,$url)==0)
{
$found = $position;
// We quit out, we don't need to go any further.
break;
}
}
}
}
fclose($file);
}
if($found)
{
$result = $real_position;
}else{
$result = 0;
}
}
return $result;
}
?>
Try urlencode() instead of the two replaces on the query.