My post falls between two If statements, what can I do? - php

Currently I'm trying to filter out various things for the meta portion of my WordPress website, and I've found an issue, using the following code was working perfectly until I needed to get a bit more specific.
if (is_singular('post')) {
$title = get_the_title ();
print '<title>'.$title.'</title>';
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
print '<meta property="og:image" content="'.$feat_image.'"/>';
print '<meta name="description" content="" />';
} else {
print '<title></title>';
print '<meta name="description" content="" />';
}
Note that I edited the meta descriptions above so that they're empty, just for the sake of posting on stack.
Then I wanted to start filtering based on the tags a post has, and obviously this is going to conflict with the already declared (is_singular('post')) function above.
However, I used the code below.
if ( has_tag( 'spanish' )) {
print '<title>'.$title.'</title>';
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
print '<meta property="og:image" content="'.$feat_image.'"/>';
print '<meta name="description" content="" />';
}
And it is displaying the meta for this portion also in the category we wish for it too, how ever it's also displaying the meta description for the other function as well, what can I do stack?

This might sound simplistic, but firstly you want to document exactly what you want to happen. Maybe make yourself a flow chart or write a couple of paragraphs. Either way, you need to know from a non-code point of view first. This will enable you to answer questions like "Does a tag take precedence over a single post?" Once you know this process, move your conditions away from output to simplify the process. Something like this:
// defaults
$title = '...';
$metaDescription = '...';
$featuredImage = '...';
// overrides for difference scenarios
if (is_singular('post')) {
// set title, etc here
}
if (has_tag('spanish')) {
// override or concatenate title, etc here
}
// output
print "<title>$title</title>";
<!-- etc etc -->

Related

WordPress get author name for singular page/post

I want to display author name for "author meta tag" , I used following code to do this, But I always get an empty string for that:
$fname = get_the_author_meta('first_name');
$lname = get_the_author_meta('last_name');
$author = trim( "$fname $lname" );
if ( $author ) { ?>
<meta name="author" content="<?php echo $author; ?>">
<?php } ?>
How can I get the current displayed page/post author name ?
Thank you
You need to check first you if you get correct values from the get_the_author_meta(). So, you will know if the problem come from the trim/condition part, or from wordpress itself.
To do this, add in your code :
echo "Here is my result : ".get_the_author_meta('first_name')." ".get_the_author_meta('last_name');
Once this test done, i'm sure you'll need to edit your question.
Take this answer as a general advice for debugging, more than a solution for your problem.
Ok, got it. The name of the author is actually displayed by php in your HTML page, but it's encapsulated in a meta tag, which is only used in the head part of your page, and don't produce any visible output for the user.
Try to use a div tag instead of the meta one, and make sure you are writing inside the body part of your page.
$fname = get_the_author_meta('first_name');
$lname = get_the_author_meta('last_name');
$author = trim( "$fname $lname" );
if ( $author ) { ?>
<div>Author: <?php echo $author; ?></div>
<?php } ?>

Wordpress conditional meta tag description

I'm currently using a conditional meta tag code in wordpress.
Everything is working fine, besides on certain pages.
code in header.php:
<meta name="description" content="<?php echo metadesc($post->ID); ?>" />
<?php }else{ ?>
<meta name="description" content="<?php bloginfo('description'); ?>" />
<?php } ?>
code in functions.php:
function metadesc($pid) {
$p = get_post($pid);
$description = strip_tags($p->post_content);
$description = str_replace ("\n","",$description);
$description = str_replace ("\r","",$description);
if (strlen($description) > 135) {
return htmlspecialchars(substr($description,0,135) . "...");
}else{
return htmlspecialchars($description);
}
}
This is what it shows when I go to the source and look at the meta tag description on the following pages:
home: (description of the home page that is defined in Wordpress general settings (check)
biography: first 135 characters of the page (check)
contact:
<meta name="description" content="[contact-form-7 id="25" title="Contact"]" />
As you can see, I only have a contact form on my contact page and it looks like I need to add a filter to the script so that it ignores script tags and short codes, and that it will place the homepage description instead.
How can I fix this issue?
What if you use the strip_shortcode function try this one
function metadesc($pid) {
$p = get_post($pid);
$description = strip_tags($p->post_content);
$description = str_replace ("\n","",$description);
$description = str_replace ("\r","",$description);
$description =strip_shortcodes($description );
if(empty($description )){
return please get home page content
}
else{
if (strlen($description) > 135) {
return htmlspecialchars(substr($description,0,135) . "...");
}else{
return htmlspecialchars($description);
}
}
}
strip_shortcodes
You're jumping in and out of PHP too often, which leads to coding mistakes and slow execution. Rewrite your first code:
<?php
echo '<meta name="description" content="' .
((some condition)? metadesc($post->ID): bloginfo('description')) . '" />';
?>
Now, if your raw data for the content is [contact-form-7 id="25" title="Contact"] what are you trying to turn this into? How would you like to see it reformatted? This is coming from the metadesc() function? I don't think that HTML entities in a description tag are going to be expanded to their characters, but will be used as-is. So, you might need to output [contact-form-7 id=\"25\" title=\"Contact\"] instead. Regardless, that's a very poor description -- what do you really want there?
Also be aware of whether you're in UTF-8 or a single byte encoding such as Latin-1, which becomes important when using substr() (you don't want to chop in the middle of a multibyte UTF-8 character). Also, if you're adding an ellipsis (...), you would want to take 132 characters and not 135.
I did something similar to this, conditionally taking the excerpt and using it as the description if the viewer is on a single post page & there is an excerpt. Here's the code:
<?php
if (is_single() && $post->post_excerpt != “”) {
$post = $wp_query->post;
$descrip = strip_tags($post->post_excerpt);
echo ‘<meta name=”description” content=”‘.$descrip.’”>’;
}
?>
I also wrote a blog post detailing the whole thing.

Correctly set meta description in header.php

I'm building a website with wordpress and a bought template. I added some functionality to the options/page creation. One can set a general meta description in the options and a meta description for each page while creating it.
Although I'm entirely new to PHP, I managed to add everything necessary to my code. It wasn't all that hard and it works just fine. My questions are: Am I doing it right? How can I optimize my solution? What are the downsides of my approach?
HTML (header.php):
<?php
// Defining a global variable
global $page_meta_description;
// Initializing the variable with the set value from the page
$page_meta_description= get_post_meta($post->ID, MTHEME . '_page_meta_description', true);
// Add meta tag if the variable isn't empty
if ( $page_meta_description != "" ) { ?>
<meta name="description" content="<?php echo $page_meta_description; ?>" />
<?php }
// Otherwise add globally set meta description
else if ( of_get_option('main_meta_description') ) { ?>
<meta name="description" content="<?php echo of_get_option('main_meta_description'); ?>" />
<?php }
// Set global meta keywords
if ( of_get_option('main_meta_keywords') ) { ?>
<meta name="keywords" content="<?php echo of_get_option('main_meta_keywords'); ?>" />
<?php } ?>
You can use the wp_head hook.
// write this in your plugin
add_action('wp_head', 'myplugin_get_meta_tags');
function myplugin_get_meta_tags()
{
$content = '';
$content .= '<!-- add meta tags here -->';
return $content;
}
I think this is slightly more elegant that doing all the logic in the header.php file.
If you don't want to create a plugin for this, or it's needed for a single theme, you can add this code in the functions.php file in your theme (check the link for more info).
Note
The downside(s) to your solution are:
If you ever need to create a new template that uses a different header, you need to copy the meta code to each new file, and when you make changes, make them in all header files
The template files should have as little logic in them as possible, and having a bunch of ifs would clutter it unnecessarily.

Using PHP to generate rel canonical on multiple pages within the same category (and using the glob( ) function)

Let's say you work for a company that has a reasonably large e-commerce website with lots of product categories and subcategories (and sometimes, sub-subcategories). As such, for the ease of the user, there are some categories that have duplicate subcategories w/ duplicate content. You'd like to use PHP to generate a rel canonical whenever the user lands on one of these duplicate categories and point it towards the more SEO friendly category. In this case, the category w/ duplicate subcategories is "random-stuff" and the category I'd like the canonical to point to is "assorted-things". So, item_1.html - item_4.html are all found in both "random-stuff" and "assorted-things", but I'd like the canonical to point to "assorted-things". At present, here's what I have:
<?php if(is_numeric(strpos($_SERVER['REQUEST_URI'],'random-stuff/item_1.html'))) echo '<link rel="canonical" href="http://mydomain.com'.str_replace('random-stuff', 'assorted-things', $_SERVER['REQUEST_URI']).'" />'; ?>
<?php if(is_numeric(strpos($_SERVER['REQUEST_URI'],'random-stuff/item_2.html'))) echo '<link rel="canonical" href="http://mydomain.com'.str_replace('random-stuff', 'assorted-things', $_SERVER['REQUEST_URI']).'" />'; ?>
<?php if(is_numeric(strpos($_SERVER['REQUEST_URI'],'random-stuff/item_3.html'))) echo '<link rel="canonical" href="http://mydomain.com'.str_replace('random-stuff', 'assorted-things', $_SERVER['REQUEST_URI']).'" />'; ?>
<?php if(is_numeric(strpos($_SERVER['REQUEST_URI'],'random-stuff/item_4.html'))) echo '<link rel="canonical" href="http://mydomain.com'.str_replace('random-stuff', 'assorted-things', $_SERVER['REQUEST_URI']).'" />'; ?>
It works, but it's a lot of clutter. I'd prefer to have one line of code that checked for item-1.html - item4.html instead of four checks. Does anyone have an idea of how this could be achieved?
ALSO, bare in mind that item_1.html - item_4.html are NOT the only things in "random-stuff", they're just the duplicate categories shared w/ "assorted-things". Thanks!!
UPDATE:
Marty suggested using the glob() function to loop through all files in the directory and echo only what I needed. Here's the code I came up with as a result:
$dir = 'http://www.mydomain.com/random-stuff/*';
foreach(glob($dir) as $file) {
if($file == 'item_1.html' || 'item_2.html' ||'item_3.html' ||'item_4.html') {
echo '<link rel="canonical" href="http://mydomain.com'.str_replace('random-stuff', 'assorted-things', $_SERVER['REQUEST_URI']).'" />';
}
}
This still doesn't seem to work. Can anyone illuminate me further? Am I fundamentally misunderstanding something here?
Here's a better solution: - sorry, by the way, I understood your question wrong -
// First, get last portion of url
$filename = end(explode('/',$_SERVER['REQUEST_URI']));
// Check if the same filename exists in 'assorted-things' directory:
if (file_exists("../assorted-things/$filename")) {
// If so, echo canonical
echo '<link rel="canonical" href="http://mydomain.com/assorted-things/' . $filename . '" />';
}

Add to page title tag based on variable from URL

I have seen the following thread but it's a bit beyond me...
How can I change the <title> tag dynamically in php based on the URL values
Basically, I have a page index.php (no php in it just named to future proof - maybe now!). It contains numerous lightbox style galleries which can be triggered from an external link by a variable in the URL - e.g. index.php?open=true2, index.php?open=true3, etc.
I would like the index.php title tag - to include existing static data + append additional words based on the URL variable - e.g. if URL open=true2 add "car gallery", if URL open=true3 add "cat gallery", if URL has no variable append nothing to title.
Can anyone assist? I have been searching but either missed the point of posts or it hasn't been covered (to my amateaur level).
Many thanks. Paul.
At the top of your php script put this:
<?php
# define your titles
$titles = array('true2' => 'Car Gallery', 'true3' => 'Cat Gallery');
# if the 'open' var is set then get the appropriate title from the $titles array
# otherwise set to empty string.
$title = (isset($_GET['open']) ? ' - '.$titles[$_GET['open']] : '');
?>
And then use this to include your custom title:
<title>Pauls Great Site<?php echo htmlentities($title); ?></title>
<title>Your Static Stuff <?php echo $your_dyamic_stuff;?></title>
<?php
if( array_key_exists('open', $_GET) ){
$title = $_GET['open'];
}else{
$title = '';
}
?>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
The content of the document......
</body>
</html>
http://www.w3schools.com/TAGS/tag_title.asp
http://php.net/manual/en/reserved.variables.get.php
PHP can fetch information from the URL querystring (www.yoursite.com?page=1&cat=dog etc). You need to fetch that information, make sure it's not malicious, and then you could insert it into the title. Here's a simple example - for your application, make sure you sanitise the data and check it isn't malicious:
<?php
$open = "";
// check querystring exists
if (isset($_GET['open'])) {
// if it does, assign it to variable
$open = $_GET['open'];
}
?>
<html><head><title>This is the title: <?php $open ?></title></head>
PHP has lots of functions for escaping data that might contain nasty stuff - if you look up htmlspecialchars and htmlentities you should find information that will help.
Some of the other answers are open to abuse try this instead:
<?php
if(array_key_exists('open', $_GET)){
$title = $_GET['open'];
} else {
$title = '';
}
$title = strip_tags($title);
?>
<html>
<head>
<title><?php echo htmlentities($title); ?></title>
</head>
<body>
<p>The content of the document......</p>
</body>
</html>
Otherwise as #Ben has mentioned. Define you titles in your PHP first to prevent people from being able to directly inject text into your HTML.

Categories