Add a field from a node into page.tpl.php, drupal 7 - drupal

Creating a sub-theme in Drupal 7's page.tpl.php and needing to pull the value (plain text) from field_EXAMPLE from a custom content type outside of where the rest of the content would normal be.
<!-- Adding $title as normal-->
<?php print render($title_prefix); ?>
<?php if (!empty($title)): ?>
<h1><?php print $title; ?></h1>
<?php endif; ?>
<?php print render($title_suffix); ?>
<!-- THE ISSUE: Adding field_EXAMPLE -->
<h2> <?php print render($field_EXAMPLE;);?> </h2>
...
<!-- Where the rest of the content loads by default -->
<div><?php print render($page['content']); ?></div>
Would field_get_items work?
function field_get_items($entity_type, $entity, $field_name, $langcode = NULL) {
$langcode = field_language($entity_type, $entity, $field_name, $langcode);
return isset($entity->{$field_EXAMPLE}[$langcode]) ? $entity->{$field_name}[$langcode] : FALSE;
}
Or this?
$node = node_load($nid);
$node->field_EXAMPLE[$node->language][0]['value'];
Do I put this in page.tpl.php?
Tried them but no dice. -Novice
Here is var_dump(get_defined_vars());
["field_thestring"]=>
array(1) {
["und"]=>
array(1) {
[0]=>
array(3) {
["value"]=>
string(44) "This is a string of text please refer to me "
["format"]=>
NULL
["safe_value"]=>
string(44) "This is a string of text please refer to me "
}
}
}

Lets assume that you created a field called field_thestring that you want to render for a content type article's page at a location outside of THEME's outside of where page's content renders.
Step 1. Copy the theme's page.tpl.php. and rename it page--article.tpl.php.
Step 2. In page.var.php,
function THEME_preprocess_page(&$variables) {
// To activate page--article.tpl.php
if (isset($variables['node']->type)) {
$nodetype = $variables['node']->type;
$variables['theme_hook_suggestions'][] = 'page__' . $nodetype;
}
// Prevent errors on other pages
if ($node = menu_get_object()) {
if ( !empty($node) && $node->type == 'article') {
$fields = field_get_items('node', $node, 'field_thestring');
$index = 0;
$output = field_view_value('node', $node, 'field_thestring', $fields[$index]);
$variables['thestring'] = $output;
}
else{
$variables['thestring'] = 'Angry Russian: How this error?';
}
}
}
Step 3. In page--article.tpl.php add <?php print render($thestring); ?>
Initially, I wanted to require all content types to have another field since all Content Types has a Title. Determined it wasn't a great idea for further development.
Source

$node = node_load($nid);
$example_value = $node->field_EXAMPLE[$node->language][0]['value'];
<h2> <?php print $example_value;?> </h2>
or,
$node = node_load($nid);
$values = field_get_items('node', $node, 'EXAMPLE');
if ($values != FALSE) {
$val = $values[0]['value'];
}
else {
// no result
}
<h2> <?php print $example_value;?> </h2>

You can place your code directly into page template, but you can also place it in page preprocess hook, set the template variable and use that variable from your page template:
https://api.drupal.org/api/drupal/includes%21theme.inc/function/template_preprocess_page/7.x
It's kinda cleaner way, but both should work.
Also, try deleting Drupal's cache if you don't see your change immediately on front-end.
And for getting node id try:
global $node;
$nid = $node->nid;
$node = node_load($nid);
...
And if that doesn't work try this:
if ($node = menu_get_object()) {
// Get the nid
$nid = $node->nid;
$node = node_load($nid);
...
}
or this way:
if (arg(0) == 'node' && is_numeric(arg(1))) {
// Get the nid
$nid = arg(1);
$node = node_load($nid);
...
}

You can use a preprocess to add value into $variables passed to template
https://api.drupal.org/api/drupal/includes%21theme.inc/function/template_preprocess_page/7.x
In template.php :
MYTHEMENAME_preprocess_page(&variable){
$values = current(field_get_items('node', $variable['node'],'field_machine_name'));
$variable['myvar'] = $values['value'];
}
In your template.tpl.php
echo $myvar; // contains your value

Related

remove html from the titles of Post and Page Columns of wordpress dashboard

I would like to remove HTML from the titles of Post and Page Columns of wordpress dashboard as in the image attached.
Normally wordpress wont have html tags in the title.But as part of a plugin creation i need to remove these htmls tags .I am trying to create a Tynimce editor to the title fields
Any suggestions?
Well, that HTML is right in your title-field.
Why is it there? It´s absolutely not the right place for markup.
// Replace your Title Column with the Existing one //
function replace_title_column($columns) {
$new = array();
foreach($columns as $key => $title) {
if ($key=='title')
$new['new-title'] = __(Title); // Our New column Name
$new[$key] = $title;
}
unset($new['title']);
return $new;
}
// Replace the title with your custom title
function replace_title_products($column_name, $post_ID) {
if ($column_name == 'new-title') {
$cont = get_the_title();
$cont = str_replace('<', '<', $cont);
$cont = str_replace('>', '>', $cont);
$cont = str_replace('"', '"', $cont); ?>
<a class="row-title" href="<?php echo esc_url( home_url( '/' ) ); ?>wp-admin/post.php?post=<?php echo $post_ID; ?>&action=edit"><?php echo strip_tags($cont); ?></a>
<?php
}
}
add_filter('manage_posts_columns', 'replace_title_column');
add_action('manage_posts_custom_column', 'replace_title_products', 10, 2);
add_filter('manage_pages_columns', 'replace_title_column');
add_action('manage_pages_custom_column', 'replace_title_products', 10, 2);

How can I apply this to my theme's functions.php file, rather than a core WordPress file?

I need to apply a class to the post archive links that are output by WordPress' get_archive_links function. I can accomplish this by modifying /wp-includes/general-template.php (line 842), from this:
$link_html = "\t<li>$before<a href='$url' title='$title_text'>$text</a>$after</li>\n";
to this:
$link_html = "\t<li>$before<a class='hello' href='$url' title='$title_text'>$text</a>$after</li>\n";
I'm pretty sure I need to add some sort of filter in my theme's functions.php to accomplish this the smart way, without modifying a core file, I just don't know how. Any guidance would be awesome.
EDIT: Here is the entire, unmodified function from general-template.php:
function get_archives_link($url, $text, $format = 'html', $before = '', $after = '') {
$text = wptexturize($text);
$title_text = esc_attr($text);
$url = esc_url($url);
if ('link' == $format)
$link_html = "\t<link rel='archives' title='$title_text' href='$url' />\n";
elseif ('option' == $format)
$link_html = "\t<option value='$url'>$before $text $after</option>\n";
elseif ('html' == $format)
$link_html = "\t<li>$before<a href='$url' title='$title_text'>$text</a>$after</li>\n";
else // custom
$link_html = "\t$before<a href='$url' title='$title_text'>$text</a>$after\n";
$link_html = apply_filters( 'get_archives_link', $link_html );
return $link_html;
}
So I figured out how to do this, thanks to this page.
Just throw this in functions.php:
// Filter to add nofollow attribute
function nofollow_archives($link_html) {
return str_replace('<a href=', '<a rel="nofollow" href=', $link_html);
}
Then call the new function wherever you'd like:
<?php add_filter('get_archives_link', 'nofollow_archives'); ?>
<?php wp_get_archives('type=monthly'); ?>
The example is obviously showing how to add a nofollow rel tag, but you can easily modify it to add a link class or anything else.
how about something like this?
function new_get_archives_link ( $link_html ) {
if ('html' == $format) {
$link_html = "\t<li>$before<a class='hello' href='$url' title='$title_text'>$text</a>$after</li>\n";
}
return $link_html;
}
add_filter("get_archives_link", "new_get_archives_link");
copy this into your functions.php and you shouldnt have to edit core files.
untested..

How to display WordPress RSS feed your website?

Hello i have a website and a blog, i want to display my self hosted wordpress blog on my website.
I want to show only 3 post on my website.
I want to automatically check for any new post everytime when i reload my website, so that the recent three gets displayed only.
I want to show the complete title of my wordpress blogpost but specific letters of description.
Also the description should end up with a word not some piece of non-dictionary word ending with "..."
How this can be done, i have heard that it can be done through RSS.
Can somebody help me?
To accomplish this you need to read the RSS of the blog, from RSS you need to read the Title and the description, after reading the whole description and title you need to trim the description to your desired number of letters. After that you need to check weather the description last word has been completed or not and then you need to remove a the last word if not completed and put the "...".
First we will make a script to trim the description and to put "..." in last:-
<?php
global $text, $maxchar, $end;
function substrwords($text, $maxchar, $end='...') {
if (strlen($text) > $maxchar || $text == '') {
$words = preg_split('/\s/', $text);
$output = '';
$i = 0;
while (1) {
$length = strlen($output)+strlen($words[$i]);
if ($length > $maxchar) {
break;
}
else {
$output .= " " . $words[$i];
++$i;
}
}
$output .= $end;
}
else {
$output = $text;
}
return $output;
}
Now we will define the variables in which we store the values:-
$xml=("http://your-blog-path/rss/");
global $item_title, $item_link, $item_description;
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);
$x=$xmlDoc->getElementsByTagName('item');
Now, we will make an array and store values in it. I am only taking 3 because you have asked it the way. You can change it to anything (The number of post you want to show, put that in the loop)
for ($i=0; $i<3; $i++)
{
$item_title[$i] = $x->item($i)->getElementsByTagName('title')->item(0)->childNodes->item(0)->nodeValue;
$item_link[$i] = $x->item($i)->getElementsByTagName('link')->item(0)->childNodes->item(0)->nodeValue;
$item_description[$i] = $x->item($i)->getElementsByTagName('description')->item(0)->childNodes->item(0)->nodeValue;
}
?>
Now echo all these values, Link is the value where your user will click and he will be taken to your blog:-
FIRST RECENT POST:
<?php echo $item_title[0]; ?>
<?php echo substrwords($item_description[0],70); ?>
SECOND RECENT POST:
<?php echo $item_title[1]; ?>
<?php echo substrwords($item_description[1],70); ?>
THIRD RECENT POST:
<?php echo $item_title[2]; ?>
<?php echo substrwords($item_description[2],70); ?>
Hope this can solve your problem. By the way Nice question.
Click here for the original documentation on displaying RSS feeds with PHP.
Django Anonymous's substrwords function is being used to trim the description and to insert the ... at the end of the description if the it passes the $maxchar value.
Full Code:
blog.php
<?php
global $text, $maxchar, $end;
function substrwords($text, $maxchar, $end='...') {
if (strlen($text) > $maxchar || $text == '') {
$words = preg_split('/\s/', $text);
$output = '';
$i = 0;
while (1) {
$length = strlen($output)+strlen($words[$i]);
if ($length > $maxchar) {
break;
} else {
$output .= " " . $words[$i];
++$i;
}
}
$output .= $end;
} else {
$output = $text;
}
return $output;
}
$rss = new DOMDocument();
$rss->load('http://wordpress.org/news/feed/'); // <-- Change feed to your site
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
);
array_push($feed, $item);
}
$limit = 3; // <-- Change the number of posts shown
for ($x=0; $x<$limit; $x++) {
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
$link = $feed[$x]['link'];
$description = $feed[$x]['desc'];
$description = substrwords($description, 100);
$date = date('l F d, Y', strtotime($feed[$x]['date']));
echo '<p><strong>'.$title.'</strong><br />';
echo '<small><em>Posted on '.$date.'</em></small></p>';
echo '<p>'.$description.'</p>';
}
?>
You can easily put this in a separate PHP file (blog.php) and call it inside your actual page.
Example:
social.php
<h3>Latest blog post:</h3>
<?php require 'blog.php' ?>
Also, this code is plug-n-play friendly.
Why not use the Wordpress REST API to retrieve posts -
API URL is : https://public-api.wordpress.com/rest/v1/sites/$site/posts/
where $site is the site id of your wordpress blog
or else simply use this plugin -
http://www.codehandling.com/2013/07/wordpress-feeds-on-your-website-with.html

WordPress: WP_Query in functions.php returns empty query (for a custom shortcode)

I'm writing a custom shortcode for a childtheme that I've dropped into my child themes functions.php. Here's the code:
function get_featured_video(){
$video_query = new WP_Query('category_name=videos&order=ASC');
$videoPath = "/";
$videoText = "";
while ($video_query->have_posts()){
$video_query->the_post();
$featured = get_post_meta($post->ID, "vid_feature", $single = true);
if(strtolower($featured)=='yes'){
$videoPath = get_permalink($post->ID);
$content = strip_tags($post->post_content);
$contentArr = str_word_count($content,1);
if(count($contentArr>50)){
$videoText = join(" ",array_slice($contentArr,0,50));
$videoText .= " <a href='$link'><read more></a>";
} else {
$videoText = $content;
}
break;
}
}
$returnStr = "<h1><a href='$videoPath'>You've Got to See This!</a></h1>\n";
$returnStr .= $videoText;
return $returnStr;
}
add_shortcode('getfeaturedvideo','get_featured_video');
The problem I'm having is that it's returning a blank query. I know there's a post in the videos category. I've never used the WP_Query inside functions.php. Is there a different method I need to use?
At the top of the function try declaring:
global $post;

Wordpress excerpt - image and text

This is the mockup I have:
http://img697.imageshack.us/img697/3172/featuresb.jpg
Each section will be an excerpt of a post that has a certain tag.
Is there any way of doing this so a client doesnt have to touch and tags or code like that?
You could filter the content with your own function.
Instead of using <?php the_content() ?> its better to use this: <?php your_function(get_the_content()) ?>
The function can be put on functions.php and you are free to code.
You can use the_content filter like so,
add_filter('the_content', 'my_content_filter'); //
function my_content_filter($content) {
global $post;
if($post->post_excerpt == ''){ // check if the post has excerpt
$content = strip_tags($content); //strip tags
$cont_array = explode(' ',$content);
if(count($cont_array) > 55) //number of words wanted in excerpt default is 55
$content = implode(' ',array_slice($cont_array, 0, 55)).'...';
$content = '<p>'.$content.'</p>';
}else{
$content = $post->post_excerpt; //copy excerpt to content
}
return $content; //return content
}
The above code checks if the post has excerpt, if it has excerpt it returns excerpt else returns first 55 words (default length for excerpt).
use this code for limit the post content.
<?php substr($post->post_content, 0, 12); ?> ...
Put this in your themes functions.php file:
function excerpt($limit) {
$excerpt = explode(' ', get_the_excerpt(), $limit);
if (count($excerpt)>=$limit) {
array_pop($excerpt);
$excerpt = implode(" ",$excerpt).'...';
} else {
$excerpt = implode(" ",$excerpt);
}
$excerpt = preg_replace('`\[[^\]]*\]`','',$excerpt);
return $excerpt;
}
then add this this in your loop:
<?php print '<p>'.excerpt(40).'</p>'; ?>

Resources