How to add content to wordpress loops? - php

I've got some if statements for my plugin that I would like to execute for every post.
For now, lets just say I want to add "Hello World" to every post
I've tried quite a few things, but I can't quite seem to figure this out.
Quite simply, in my plugin I have:
add_filter('the_post','testing');
function testing($content){
echo "Hello World";
}
Obviously I'm doing something wrong as Hello World doesn't how.
Can anyone point me in the right direction please?
Here is the working code on my index.php page of my theme:
http://pastebin.com/xd1ree8W
Id' like to put the if statement at the top, within a function in my plugin, so it loads for every post.

So this works on my install using it in the functions.php
i didnt modify the get_the_ID() parts but you could easily use the object like so $obj->ID
function everypost_func($obj){
echo 'This is sort of cool';
if (get_post_meta(get_the_ID(), 'other-link', true))
{
$url = get_post_meta(get_the_ID(), 'other-link', true);
$status = 200;
$price = NULL;
//echo "Looks like you've got other-link selected";
}
elseif (get_post_meta(get_the_ID(), 'generic-asin', true))
{
$status = 100;
$asin = get_post_meta(get_the_ID(), 'generic-asin', true);
//echo "Looks like you've got a generic-asin";
if($_COOKIE['countrycode'] == "GB")
{
$reg = "co.uk";
//echo "and we've detected you're in the UK <br>";
}
else
{
$reg = "com";
//echo "and we've detected you're not from the UK <br>";
}
}
else
{
if(($_COOKIE['countrycode'] == "GB") && get_post_meta(get_the_ID(), 'link-uk', true))
{
$asin = get_post_meta(get_the_ID(), 'link-uk', true);
$reg = "co.uk";
$status = 100;
//echo "looks like you're in the UK, and we have a UK link<br>";
}
elseif (get_post_meta(get_the_ID(), 'link-us', true))
{
$asin = get_post_meta(get_the_ID(), 'link-us', true);
$reg = "com";
$status = 100;
//echo "looks like you're not in the UK, but we have a US link for you<br>";
}
elseif (get_post_meta(get_the_ID(), 'link-uk', true)) {
$asin = get_post_meta(get_the_ID(), 'link-uk', true);
$reg = "co.uk";
$status = 100;
//echo "looks like you're not the UK, but we have a UK link<br>";
}
else
{
$status = 404;
//echo "looks like nothing is here for you<br>";
}
}
if($status == 100)
{
$results = get_aws_details($reg, $asin);
$price = $results[0][0];
$url = $results[1][0];
$wishlist = $results[2][0];
//echo "Success";
}
elseif($status == 404)
{
$price = NULL;
$url = get_the_permalink();
$wishlist = NULL;
//echo "404";
}
}
add_action('the_post','everypost_func');
So taking in consideration that you are doing it in a plugin it will depend on the context you are constructing it.
Example in OOP : add_action('the_post',array($this,'everypost_func'));
Maybe try to make it work within the theme file ie functions.php then if it works as you are expecting it then move it in your plugin surrounded with all the goodies necessary.
-- will update more upon OP commentary

You have used perfects filter for the add content but you have make slightly mistake in filter function.
here you have need add "hello word" in content. bellow filter fulfilled your requirement.
function testing($content){
return $content. "Hello World";
}
add_filter('the_post','testing');
here Hello world add on beginning of the content.
I hope it's work for you.

When I read the headline I thought the following snippet might be what you are looking for. This supposes that your chosen theme uses the
the_content()
function to render the post content. After browsing through your paste bin I'm not so sure if this snippet addresses the code you put in the paste bin, but I'm leaving it on as it does answer the headline and might point you in the right direction.
add_filter( 'the_content', 'add_my_content' );
function add_my_content( $content ) {
return "Hello World, \n" . $content;
}

Related

Generate meta page title exactly as on h1 tag

Site based on Joomla. I have many pages where h1 header is mentioned as product detail and displayed based on product details through PHP. There are 2 files: default.php and view.html.php.
default.php :
<h1>Used <?php echo $this->CatName; ?> <?php echo $this->prodDet->prod_name;?> Toy for Sale </h1>
This correctly display the h1 tag. I want to generate meta title of the page and use this h1 output as generated in view.html.php. This line defines the title of the page :
$this->document->setTitle($title);
And this line defines header h1 :
"{$this->item->heading}";
Complete code :
protected function _prepareDocument()
{
$app = JFactory::getApplication();
$menus = $app->getMenu();
$title = null;
// Because the application sets a default page title,
// We need to get it from the menu item itself
$menu = $menus->getActive();
if ($menu)
{
$this->params->def('page_heading', $this->params->get('page_title', $menu->title));
}
else
{
$this->params->def('page_heading', JText::_('COM_USEDCAR_DEFAULT_PAGE_TITLE'));
}
$title = $this->params->get('page_title', '');
if (empty($title))
{
$title = $app->get('sitename');
}
elseif ($app->get('sitename_pagetitles', 0) == 1)
{
$title = JText::sprintf('JPAGETITLE', $app->get('sitename'), $title);
}
elseif ($app->get('sitename_pagetitles', 0) == 2)
{
$title = JText::sprintf('JPAGETITLE', $title, $app->get('sitename'));
}
$title = "{$this->item->heading}";
$this->document->setTitle($title);
if ($this->params->get('menu-meta_description'))
{
$this->document->setDescription($this->params->get('menu-meta_description'));
}
if ($this->params->get('menu-meta_keywords'))
{
$this->document->setMetadata('keywords', $this->params->get('menu-meta_keywords'));
}
if ($this->params->get('robots'))
{
$this->document->setMetadata('robots', $this->params->get('robots'));
}
}
Output in title tag is heading. How to put this h1 tag output instead of $title?
Here's what the title portion of your code does:
// getting title from params
$title = $this->params->get('page_title', '');
// trying to get it right
if (empty($title))
{
$title = $app->get('sitename');
}
elseif ($app->get('sitename_pagetitles', 0) == 1)
{
$title = JText::sprintf('JPAGETITLE', $app->get('sitename'), $title);
}
elseif ($app->get('sitename_pagetitles', 0) == 2)
{
$title = JText::sprintf('JPAGETITLE', $title, $app->get('sitename'));
}
// overwrite everything above with some value, making above code useless
$title = "{$this->item->heading}";
$this->document->setTitle($title);
I might be wrong but if I recall correctly, if a value doesn't exist it will return the variable name when cast into a string. Here "heading" might be empty.
You might want to change your code to something like this:
[...]
if(!title){
if(property_exists($this, 'item') && property_exists($this->item, 'heading') && $this->item->heading){
$title = $this->item->heading;
} else {
$title = sprintf('Used %s %s Toy for Sale' , $this->CatName, $this->prodDet->prod_name);
}
}
$this->document->setTitle($title);
You might as well like to save the title to session and reuse it everywhere:
[...]
$this->document->setTitle($title);
// save title to session
$_SESSION['page_title'] = $title;
and update the previous loop:
// getting title from params
$title = (isset($_SESSION['page_title']) && $_SESSION['page_title'])? $_SESSION['page_title'] : $this->params->get('page_title', '');
if (empty($title)){
[...]
Full code would be something like that:
[...]
session_id() || session_start();
$title = (isset($_SESSION['page_title']) && $_SESSION['page_title'])? $_SESSION['page_title'] : $this->params->get('page_title', '');
if(!title){
if(property_exists($this, 'item') && property_exists($this->item, 'heading') && $this->item->heading){
$title = $this->item->heading;
} else {
$title = sprintf('Used %s %s Toy for Sale' , $this->CatName, $this->prodDet->prod_name);
}
}
if (empty($title))
{
$title = $app->get('sitename');
}
elseif ($app->get('sitename_pagetitles', 0) == 1)
{
$title = JText::sprintf('JPAGETITLE', $app->get('sitename'), $title);
}
elseif ($app->get('sitename_pagetitles', 0) == 2)
{
$title = JText::sprintf('JPAGETITLE', $title, $app->get('sitename'));
}
$_SESSION['page_title'] = $title;
$this->document->setTitle($title);
[...]
You might as well just ditch everything and go like that if you'd like:
[...]
$title = $this->params->get('page_title', '');
if(!title){
if(property_exists($this, 'item') && property_exists($this->item, 'heading') && $this->item->heading) {
$title = $this->item->heading;
} elseif(
property_exists($this, 'CatName') &&
property_exists($this, 'prodDet') &&
property_exists($$this->prodDet, 'prod_name') &&
$this->CatName &&
$this->prodDet->prod_name
){
$title = sprintf('Used %s %s Toy for Sale' , $this->CatName, $this->prodDet->prod_name);
} else {
$title = $app->get('sitename');
}
}
$this->document->setTitle($title);
[...]
Code is untested but it should put you on the right track :)
Why don't you just send your h1 content to your php-document as GET parameter and then just output the it using echo inside the title tag? Unless you avoid dinamic echoing, this could be a fine solution for outputting text as title.
I would abstract away the logic of constructing the title/header to some function and then use this function to construct the title in both places.
function constructTitle($catName, $prodName) {
return "Used {$catName} {$prodName} Toy for Sale";
}
...
[in default.php]
<h1><?php echo constructTitle($this->CatName, $this->prodDet->prod_name); ?></h1>
[in view.html.php]
$this->document->setTitle(constructTitle(..., ...));
This allows you to have a single point to format your title while using it in several places.
The function needs to, obviously, be place in such position so that it can be accessed in both places and you need to have some way to get category name and product name in view.html.php. Im not familiar enough with joomla to know these things.
Edit:
To clarify, there is no real way to "extract" the title from the default.php as it is dynamic. You would need to process the php file then maybe you could do some regex magic, but this is in no way the proper solution to the problem.
you can just send your h1 content to your php-document as GET parameter and then output the it using echo in the title tag? Unless you avoid dynamic echoing,it would work.

PHP - Apply code to subpages

I have this code:
<?php $url = JURI::getInstance()->toString();
if ($url == "http://example.com/news/latest/"){
echo "This is latest page";
} else {
echo "This is not latest page";
}
?>
What I'm trying to do is instead of 'http://example.com/news/latest/', how can I select the pages/items under /latest/. If it makes any more sense, here's a syntax:
if ($url == "http://example.com/news/latest/" + ANYTHING UNDER THIS)
I cannot use not equal to ($url !=) since it will include other parent pages not equal to /latest/. I just want what's under it. If anyone understands it, I need help on how to put it into code.
Update:
What I'm trying to do is if the page is example.com/news/latest, it will echo "Latest". And if for example, I am in example.com/news/latest/subpage1/subpage2, it will echo "You are in a page that is under Latest." Anything beyond "Latest" will echo that.
$str = 'example.com/news/latest/dfg';
preg_match('/example.com\/news\/([^\/]+)\/?(.*)/', $str, $page);
if(isset($page[2]) && $page[2])
echo 'You are under: ' , $page[1];
elseif(isset($page[1]))
echo 'At: ' , $page[1];
else
echo 'Error';
Edit: after clarification switched to regular expression.
Use a regular expression:
$matches = array();
if((preg_match('#http://example\.com/news/latest/(.*)#', $url, $matches)) === 1) {
if(strlen($matches[0]) > 0) {
echo "You're at page: $matches[0]";
} else {
echo "You're at the root";
}
} else {
// Error, incorrect URL (should not happen)
}
EDIT: Fixed, untested so you may have to tweak it a little

Php backlink checker on another website

I am trying to make a script to check if a webpage has a back link to my page. I have found this script but the problem is that it returns the error message "No back link found" even if there is a backlink. Could someone tell me what is wrong with this script?
Here is the script I am using:
require('simple_html_dom.php');
function CheckReciprocal( $targetUrl, $checkLinkUrl, $checkNofollow = true )
{
$html = file_get_html($targetUrl);
if (empty($html))
{
//# Could not load file
return false;
}
$link = $html->find('a[href^='.$checkLinkUrl.']',0);
if (empty($link))
{
//# Link not found
return false;
}
if ( $checkNofollow && $link->hasAttribute('rel') )
{
$attr = $link->getAttribute('rel');
return (preg_match("/\bnofollow\b/is", $attr) ? false : true);
}
return true;
}
$targetUrl = 'http://example.com/test.html';
$checkLinkUrl = 'http://mysite.com';
if ( CheckReciprocal($test, $checkLinkUrl) )
{
echo 'Link found';
}
else { echo 'Link not found or marked as nofollow'; }
Thank you!
I don't know how does that simple_html_dom.php's $html->find() works cos never used it, but it seems that your problem is there. I would trust the good ol' DOMDocument + regex.
Just wrote a function and tested it, just use on the $url the plain domain + whatever you want, don't worry about the http(s) or www and stuff like that:
function checkBackLink($link, $url, $checkNoFollow = true){
$dom = new DOMDocument();
$dom->loadHTMLFile($link);
foreach($dom->getElementsByTagName('a') as $item){
if($checkNoFollow){
if(preg_match('/nofollow/is', $item->getAttribute('rel'))) continue;
}
if($item->hasAttribute('href') === false) continue;
if(preg_match("#^(https?\://)?(www\.)?$url.*#i", $item->getAttribute('href'))) return true;
}
}
if(checkBacklink('the link', 'example.com')){
echo "link found";
} else {
echo "Link not found or marked as nofollow";
}
If you don't like it and still want to use the simple_html_dom just make sure how that find() works, because if it only match exact values that could be troublesome.

How to convert Meters to Foot using PHP

I have used this code which shows an error:ie if my meters is 175m but when i convert it does'nt show that thing
<?php
function metersToFeetInches($meters, $echo = true)
{
$m = $meters;
$valInFeet = $m*3.2808399;
$valFeet = (int)$valInFeet;
$valInches = round(($valInFeet-$valFeet)*12);
$data = $valFeet."′".$valInches."″";
if($echo == true)
{
echo $data;
} else {
return $data;
}
}
?>
<?php
$feetInches = metersToFeetInches(1.75,false);
echo $feetInches;
?>
This is one of those things you can easily find on Google, but I guess you didn't look further than the first link.
Anyways, you should do it like this.
<?php
function metersToFeet($meters) {
return floatval($meters) * 3.2808399;
}
?>
But why is this better than the code you posted? Well, functions are not supposed to do everything. You should write a function for a certain action, not one big function with everything you can every need. Because if you need to add something to that function or change the order of actions, it's a hell of a lot of work.
Furthermore, your function has an option $echo. But why would you need that? You can add such an option to every function, but PHP has a nice commando for that: echo. So instead, it's way better to write echo metersToFeet(10). Or $value = metersToFeet(10) if you need to save the result in a variable.
<?php
function metersToFeetInches($meters, $echo = true)
{
$m = $meters;
$valInFeet = $m*3.2808399;
$valFeet = (int)$valInFeet;
$valInches = round(($valInFeet-$valFeet)*12);
$data = $valFeet."′".$valInches."″";
if($echo == true)
{
echo $data;
} else {
return $data;
}
}
?>

Yii: Customize the results of CAutoComplete

I need to make a dropdown list using CAutoComplete. Everything is set and works fine, here is my code of the action:
<?php
public function actionSuggestCharacter() {
if(Yii::app()->request->isAjaxRequest && isset($_GET['q'])) {
$name = $_GET['q'];
$criteria = new CDbCriteria;
$criteria->condition='`Character` LIKE :keyword';
$criteria->params=array(':keyword'=>"$name%");
$criteria->limit = 5;
$suggestions = zCharacter::model()->findAll($criteria);
$returnVal = '';
foreach($suggestions as $suggestion) {
$returnVal .= $suggestion->Character."\n";
}
if (isset($suggestion)) {
echo $returnVal;
}
$criteria->condition='`Character` LIKE :keyword';
$criteria->params=array(':keyword'=>"%$name%");
$criteria->limit = 5;
$suggestions = zCharacter::model()->findAll($criteria);
$returnVal = '';
foreach($suggestions as $suggestion) {
$returnVal .= $suggestion->Character."\n";
}
if (isset($suggestion)) {
echo $returnVal;
}
}
}
?>
What this code does is that it shows the first 5 matches with the keyword at the beginning and the next 5 matches are with the keyword in any place.
Example. Let's say a user types in the input field "pdd" (doesn't really matter, could be any text), so the results returned by autocomplete will look like:
1. pddtext...
2. pddtext...
3. pdd_some_other_text
4. pdd_text
5. pdd_text
1. text_text_pdd
2. text_pdd_text
3. etc...
The problem is I need to separate these two blocks by some kind of line (<hr> or <div> with the border). How can I do this?
Thank you.
Can't you do something like this?
<?php
public function actionSuggestCharacter() {
if(Yii::app()->request->isAjaxRequest && isset($_GET['q'])) {
...
if (isset($suggestion)) {
echo $returnVal;
}
echo "Hey this is the delimiter\n";
$criteria->condition='`Character` LIKE :keyword';
....
}
}
?>
And then on the client side check for this string and when you encounter ""Hey this is the delimiter" replace it with your separator.

Categories