load a view file within a function in php/codeigniter - php

I have a function that I'd like plug a view file. It's pretty simple when you just need to echo one or two things but I have some complicated html and so would like to take advantage of alternate php syntax for the following foreach loop and if statements:
UPDATE I corrected the CI->load->view to include the 3rd parameter according to tpaksu's suggestion. It's closer to working but still not quite right. See comments below in the code:
<?
function displayComments(array $comments, $parentId = null) {
$CI=& get_instance();
foreach($comments as $comment){
if($comment['replied_to_id'] == $parentId){
echo $CI->load->view('reviews/comment_list', $comments, true); // this doesn't work, it only shows the last array member
// echo $comment['comment']; this works as expected
}
}
}
displayComments($comments, $parentId = null);
?>
Here's what the 'reviews/comment list view file looks like in its simplest form:
<ul>
<? foreach($comments as $comment): $comment=$comment['comment']?>
<li>
<?echo $comment?>
</li>
<?endforeach;>
</ul>
Would anyone know to how embed view files into a function?

I usually use to have a snippet_helper in my projects. There, I have many many functions wich generates chunks of reusable things (also called modules or components).
I do like, also, the WordPress approach wich use to return data in the main function (you may need more treatments before display) and a "sister function" to directly echo the results.
I think it'll works with you. For example:
function get_display_comments(array $comments, $parentId = NULL)
{
$CI =& get_instance();
$return = '';
foreach ($comments AS $comment)
{
if ($comment['replied_to_id'] == $parentId)
{
$return .= $CI->load->view('reviews/comment_list', $comments, TRUE);
}
}
return $return;
}
function display_comments(array $comments, $parentId = NULL)
{
echo get_display_comments($comments, $parentId);
}

Your content on the first file :
<?php
$CI=& get_instance();
echo $CI->load->view('reviews/comment_list', $comments, true);
?>
And the reviews/comment_list view :
<ul>
<?php
foreach($comments as $comment){
$comment=$comment['comment'];
echo "<li>" . $comment . "</li>";
}
?>
</ul>
just write this and try again.

Related

Unable to print links in another function

I've written some code in php to scrape some preferable links out of the main page of wikipedia. When I execute my script, the links are coming through accordingly.
However, at this point I've defined two functions within my script in order to learn how to pass links from one function to another. Now, my goal is to print the links in the latter function but it only prints the first link and nothing else.
If I use only this function fetch_wiki_links(), I can get several links but when i try to print the same within get_links_in_ano_func() then it prints the first link only.
How can I get them all even when I use the second function?
This is what I've written so far:
include("simple_html_dom.php");
$prefix = "https://en.wikipedia.org";
function fetch_wiki_links($prefix)
{
$weblink = "https://en.wikipedia.org/wiki/Main_Page";
$htmldoc = file_get_html($weblink);
foreach ($htmldoc->find("a[href^='/wiki/']") as $a) {
$links = $a->href . '<br>';
$absolute_links = $prefix . $links;
return $absolute_links;
}
}
function get_links_in_ano_func($absolute_links)
{
echo $absolute_links;
}
$items = fetch_wiki_links($prefix);
get_links_in_ano_func($items);
Your function returned the value at the very first iteration. You will need something like this:
function fetch_wiki_links($prefix)
{
$weblink = "https://en.wikipedia.org/wiki/Main_Page";
$htmldoc = file_get_html($weblink);
$absolute_links = array();
foreach ($htmldoc->find("a[href^='/wiki/']") as $a) {
$links = $a->href . '<br>';
$absolute_links []= $prefix . $links;
}
return implode("\n", $absolute_links);
}

Can't get data-title, just data-slug

HTML
<article class="movie-summary" data-slug="slug-goes-here" data-title="This is a Title">
...
...
</article>
PHP
$html = file_get_html( 'example.com' );
foreach( $html->find('article') as $data) {
$property = 'data-title';
echo $data->$property;
}
Hey all, so I want to be able to get all data-title from all articles off a particular site. When I use data-slug I get data back yet when I use data-title I get nothing, with the help of this post
If you look at the actual HTML code you are trying to parse (the link provided at comments), you see that it is not valid:
<article class="movie-summary hero" data-slug="aiyaary-hindi"data-title="Aiyaary">
...
</article>
Meaning, there is no space between data-slug and data-title attributes. So to fix this I suggest to add necessary spaces. Like so:
function placeNeccessarySpaces($contents) {
return preg_replace('/"data-title/', '" data-title', $contents);
}
This is similar to this answer. Then:
$contents = placeNeccessarySpaces(file_get_contents('http://example.com'));
$html = str_get_html($contents);
foreach( $html->find('article') as $data) {
$property = 'data-title';
echo $data->$property;
}
This is simply working fine, Verified result
<?php
include 'simple_html_dom.php';
$html = str_get_html('<article class="movie-summary" data-slug="slug-goes-here" data-title="This is a Title"></article>');
foreach( $html->find('article') as $data) {
$property = 'data-title';
echo $data->$property;
}
?>
got the file 'simple_html_dom.php' from https://sourceforge.net/projects/simplehtmldom/files/
output:

SimpleXml foreach : ignore element

<?php
$xml = "<articles>
<article id=\"18357302\">
<articleCategories>
<articleCategory id=\"default\"/>
<articleCategory id=\"66607\"/>
</articleCategories>
</article>
</articles>";
$feed = simplexml_load_string($xml);
$items = $feed->article;
foreach ($items as $article) {
// $categorie = $article->articleCategories->articleCategory[id];
$categories = $article->articleCategories;
print_r($categories);
echo "<br>print_r indeed returns an array, but impossible to echo it using foreach!!!<br>";
foreach ($categories->id as $category) {
if ($category != "default") {
echo $category;
}
}
}
?>
not sure what i am doing wrong, i am just trying to find a way to remove the part with the default value inside articlesCategories
<articleCategory id=\"default\"/>
The script needs to ignore this part and just use the next articleCategory from the XML file, and i would prefer to avoid removing it with regex
The script iterates over articleCategories tag.
But it needs to iterate over articleCategory tag.
The following changes will be enough.
foreach ($categories->articleCategory as $category) {
if ($category["id"] != "default") {
echo $category["id"];
}
}

Php syntax for echoing multiple classes with a space between them

I'm am working on a Wordpress custom template and I'm filtering post by their classes.
Since Wordpress displays a LOT of unnecessary classes when I put <?php post_class(); ?> in a page, ( here is what it gives me class="post-54 post type-post status-publish format-standard hentry category-3d category-web" )
I'm trying to simplify that by echoing only the categories that relate to the post.
EDIT: This is what calls the post in my page <?php query_posts( 'showposts=99' ); ?>
Then this piece of code
<li class="<?php if ( in_category('category-3d')) { echo "3d"; }
if ( in_category('category-animation')) { echo "animation"; }
if ( in_category('category-motion')) { echo "motion"; }
if ( in_category('category-shortfilm')) { echo "shortfilm"; }?>"></li>
give me this <li class="motion"></li> if my post is in the "motion" category.
The problem is that if my post is in several categories, only the first is echoed... How can I tell WP to echo ALL the names of the categories my post is affected to, while adding a space between them?
Since I am a beginner in php syntax, I'm still learning how to get such a simple thing working in a clean and effective way (i.e. without writing 16 lines of code !)...
Can someone help me on this one?
SECOND EDIT:
Ok I'm still trying to figure out why, but today, my piece of code (above) is working and echoes all my listed classes, but without space between them... So to make my classes work, I'm adding a space at the end of the echo part like this { echo "3d "; }. But I feel like it's a dirty way to make things work...
How to add a space between each class tag in the proper way? I'm aiming for something like this foreach $categories as $cat { echo $cat . " "; } but where $categories and $cat would refer to each "if" statement.
I'm not familiar with WP but if you get your categories with some function like get_categories() then you can use implode to make a string from all categories.
<?php $categories = get_categories(); ?>
<?php $categories = implode(' ', $categories); ?>
<li class="<?php echo $categories; ?>">...</li>
Could you provide what is returning get_categories()?
EDIT:
function get_class_attr() {
$classes = get_post_class();
$classes = substr($classes, 7, -1);
$arr = array();
$arr = explode(' ', $classes);
$classes = 'class="';
foreach($arr as $class_name) {
if(strpos($class_name, 'category-') !== false) {
$classes .= substr($class_name, 9).' ';
}
}
$classes = substr_replace($classes, '"', -1, 1);
echo $classes;
}
get_class_attr(); // output: class="3d web"
Also note that 3d is not a valid class name, you can use something like movie3d or film3d.
Alternative way is to create your class value a little bit earlier and then echo it:
<?php
$classes = array();
if ( in_category('category-3d')) { $classes[] = "3d"; }
if ( in_category('category-animation')) { $classes[] = "animation"; }
if ( in_category('category-motion')) { $classes[] = "motion"; }
if ( in_category('category-shortfilm')) { $classes[] = "shortfilm";}
if(count($classes)) {
$classes = implode(' ', $classes);
} else {
$classes = '';
}
?>
<li class="<?php $classes ?>"></li>
As of the code you've posted, it should add all the categories if the product is in all the four specified ones. You could add the space between the quotes after each echo, e.g.: echo ' motion'.
I would use another approach, adding really all categories, without the need to check them by name:
<li class="<?php echo implode( ' ', get_categories() ); ?>"> … </li>
See: http://codex.wordpress.org/Function_Reference/get_categories on how to filter the output of the function get_categories().
I would suggest instead you use this function from the Wordpress API - something you should read a lot of.
Something like this should work:
<?php $categories = get_categories(); ?>
<li class="<?php foreach ($categories as $cat) {
echo $cat . " ";
}?>"> -- Your li text --
</li>

How do I nest a wordpress function inside another wordpress function?

I'm working on a wordpress theme and I'm trying to call the parent category's name to pull the appropriate page template.
I can get the call function to echo the correct name, but when I try to nest it the function doesn't run. I saw that I needed to use { } since I was already inside php but it still isn't working right. Can someone straighten me out?
This gives the correct output:
<?php $category = get_the_category();
$parent = get_cat_name($category[0]->category_parent);
if (!empty($parent)) {
echo '' . $parent;
} else {
echo '' . $category[0]->cat_name;
}
?>
. . . so I created a category_parent.php file with that in it.
This is what I'm trying to nest it in:
<?php get_template_part( ' ' ); ?>
Like this:
1.
<?php get_template_part( '<?php get_template_part( 'category_parent' ); ?>' ); ?>
or this
2.
<?php get_template_part( '{get_template_part( 'category_parent' ); }' ); ?>
Neither one works.
I really don't know if this is what you want as I did not try to make sense of what you are doing. However, generally speaking, you do this:
<?php get_template_part( get_template_part( 'category_parent' ) ); ?>
Edit:
I looked up what get_template_part() does in WP, and I think Felix Kling's answer is what you need. There is a big difference between sending something to the screen and assigning it to a variable.
<?php
echo 'filename';
?>
If you include that file, you will see filename in the browser. PHP knows nothing about it. (Okay, it could if you made use of output buffering functions, but that's besides the point...)
However if you do something like:
<?php
$x = 'filename';
?>
You can now use it in your function:
<?php
get_template_part($x);
?>
So what Felix is telling you to do is to put the logic that you currently have into a function. In this example:
<?php
function foo()
{
return 'filename';
}
get_template_part(foo());
?>
Now whatever value foo() returns will be sent to your get_template_part().
Taking your code:
$category = get_the_category();
$parent = get_cat_name($category[0]->category_parent);
if (!empty($parent)) {
$name = $parent;
} else {
$name = $category[0]->cat_name;
}
get_template_part($name);
You could take Felix's answer and put it into a file called category_parent.php, and then use it like:
require_once 'category_parent.php'
get_template_part(getName());
Honestly I am not so familiar with Wordpress, but it seems to me, you could do:
function getName() {
$category = get_the_category();
$parent = get_cat_name($category[0]->category_parent);
if (!empty($parent)) {
return '' . $parent;
} else {
return '' . $category[0]->cat_name;
}
}
get_template_part(getName());
konforce is correct about the syntax and, like konforce, I have no idea what you are trying to do. You do not need to use { } because your are not trying to dynamically name a variable and you certainly don't need to escape to php using <?php ?>, as (1) you are already in php and (2) it will stop interpreting PHP and assume html the second it hits the first '?>'.
There is no special syntax for nesting functions. Simply:
get_template_part(get_template_part('category_parent'));
is the syntax, but I have no idea what the function is or does, so I have no idea if that will work.
To debug, why don't you try this:
$parent = get_template_part('category_parent');
echo 'parent: ' . $parent . '<br />';
$result = get_template_part($parent);
echo 'result: ' . $result . '<br />';
When using variables in php strings, you will need to use double quotes ("). I assume option 2 should work then.

Categories