Dynamic array associating a custom field and a name - php

Working with wordpress function.
I have to make a function which is already made with static info, to be dynamic.
I am creating a custom field so that user can insert that info.
I need to pass an array of links associated with a name, which would be perhaps some post name.
The current code has the following structure:
function my_function() {
$First_link = 'http://www.myurl.com.br';
$Second_link = 'http://www.mysecondurl.com.br';
...etc
$allthose_links = array(
$First_link => 'First Quiz',
$Second_link => 'Second Quiz',
...etc
);
return $allthose_links;
}
I need this to be something like:
function my_function() {
$posts = get_posts($args);
$allthose_links[] = array();
foreach( $posts as $post ) {
$thelink = get_field( $post=>['mylink']);
$thename = $post->name;
}
$allthose_links = array( //here's the deal
$thelink => $thename
)
return $allthose_links;
}

The $allthose_link array should be inside the foreach loop so that each of the links will be added to $allthose_link array on every iteration using the link as the key. Your new function should look like the example below:
function my_function() {
$posts = get_posts($args);
$allthose_links = array();
foreach( $posts as $post ) {
$thelink = get_field( $post=>['mylink']);
$thename = $post->name;
$allthose_links[$thelink] = $thename;
}
return $allthose_links;
}

Related

Echo the current page title inside a get_posts() WordPress function not working

I am trying to fetch data from another custom post type books into the readers. I have written the code and the data shows up.
The challenge is that I want to check the echoed data $c[0] against the title of the current page.
Whenever I call the get_the_title() function I am instead getting the title of the other custom post type books. So there is no way I can add an if like so:
if (get_the_title()===$c[0]) {
//The echo code - see echo part of my code
}
When I echo the code, it goes into the top part of the page instead of inside the content area. I am suspecting this is the reason why I can't get the page title. I have tried researching on hooking to the content area and tried but I instead get a bunch of errors.
<?php
$posts = get_posts(array(
'numberposts' => 10,
'post_type' => 'fixtures-results'
));
if($posts)
{
foreach($posts as $post)
{
setup_postdata( $post );
$matches = str_replace("|% ","|%",get_field('fixtures_results'));
preg_match_all("#[A-z0-9 ./'áàâäãåǻăāąấấặắǎȧạàãáćĉċčççďđḑḋḍdéèêëĕěēęėềẽȩẹéĝ
ğġģǧǵḡĥħȟḣḥḩíìîïĭїĩīįǐĪỊ̣iỊǏĨị̣ịıíĵķǩḱḳļľŀĺĺóòôöõðőŏōỏǒǫȯoøồớòóõöñńņňʼnŋǹṅṇ
ŕŗřṙṛśŝşšṡṣşșţťŧțṫṭtúùûüůūűųũŭǔǘǚǜụuưüúŵŷýÿўỹẏỳỵyẙȳẙźżžẑẓḅḟḿṁṃṕṗṽṿḷẁẃẅẉẘ
ẘẋẍÒÓÔÕÖŐǑǪŌȮØÙÚÛǓǗǙǛŨŮŰŲÜỤŪĆĈČÇÀÁÂÃÄÅẠĄĀȦǍÈÉÊËĖĘĚẸẼĒȨḾṀṂŚŜŞŠṠṢŹŻŽẐẒŃŅŇ
ṄṆÑǸḢḤḨĤȞĹĻĽĿŢŤṪṬŖŘṘṚĜĠĢǦǴḠẀẂẄẈŴḊḌḐĎĐÐṔṖĶǨḰḲẊẌṼṾỴỸỲẎŸȲŶÝĴȷḄḞḶŁłÏÎÍÌıİ
ßıs-]+#[^#]+#", $matches, $countries);
$results = [];
foreach ($countries[0] as $c) {
$c = explode("#", $c);
$country_name = $c[0];
$results[$country_name] = [];
$params = explode("%", $c[1]);
foreach ($params as $key) {
if (!empty($key)) {
$test = explode("|", trim($key, '|'));
echo get_the_title($postID);
//echo $c[0] . $test[0] . $test[1] . $test[2].'<br>';
}
}
}
}
wp_reset_postdata();
}
?>
I have tried but can't get past that point. Thanks.

CakePHP Tags Model

I have a simple app that has Posts and Tags.
A post can have multiple tags and tags can belong to multiple posts. The basic DB schema is like this:
post table:
id
title
slug
content
tag table:
id
title
slug
tag_posts table:
id
tag_id
post_id
So when a user saves a post it will take a list of tags in a field and then first check if the tags exist. If the tag doesn't exist, then create them, or if not get there existing ids. (all tags are lower-cased so you can't have Tag and tag). The tags are then linked to the post by adding the ids into the tag_posts table.
This works so far, but the code to do it is really horrible. I have the following method in the Tag model which takes the list of tags and does the above:
public function savePostTags($postId, $tags)
{
// Explode the topics by comma, so we have an array to run through
$tags = explode(',', $tags);
// Array for collecting all the data
$collection = array();
//debug($tags);
function is_array_empty( $mixed ) {
if ( is_array($mixed) ) {
foreach ($mixed as $value) {
if ( ! is_array_empty($value) ) {
return false;
}
}
} elseif ( ! empty($mixed) ) {
return false;
}
return true;
}
if(is_array_empty($tags) ) {
return false;
}
// First of all we bin off existing associations to make sure we don't duplicate
// NOTE: The false means don't delete the topics or posts related!!! VERY IMPORTANT!
$this->TagPost->deleteAll(array('TagPost.post_id' => $postId), false);
$tags = array_unique($tags);
// Make sure all tags are unique
foreach($tags as $tag)
{
// Trim it so remove unwanted white spaces in the beginning and the end.
$tag = trim($tag);
// If tag is empty exit here
if(empty($tag) ) {
return false;
}
// Make it all lowercase for consistency of tag names
$tag = strtolower($tag);
// Check if we already have a topic like this
$controlFind = $this->find(
'first',
array(
'conditions' => array(
'title' => $tag
)
)
);
//debug($controlFind);
// No record found (create new tag and link it up)
if(!$controlFind)
{
$this->create();
if(
!$this->save(
array(
'title' => $tag,
'slug' => Inflector::slug($tag)
)
)
)
{
// If only one saving fails we stop the whole loop and method.
return false;
}
else
{
$temp = array(
'TagPost' => array(
'tag_id' => $this->id,
'post_id' => $postId
)
);
}
}
else // Or if found link it with the post
{
$temp = array(
'TagPost' => array(
'tag_id' => $controlFind['Tag']['id'],
'post_id' => $postId
)
);
}
$collection[] = $temp;
}
return $this->TagPost->saveAll($collection, array('validate' => false));
}
Any ideas on how to refactor this?
As it feels really long-winded and seems to break the conventions of CakePHP.
Try this
public function savePostTags($postId, $tags)
{
$tags = explode(',', $tags);
foreach($tags as $key=>$value){
$listTags[$key] = trim(strtolower($value));
}
# find the list of existing tags
$listOfExistingTags = $this->find('list',
array('conditions' => array('title' => $tags),
'recursive' => -1));
$newTags = array_diff($tags, $listOfExistingTags);
#save new tags
foreach($newTags as $key=>$value){
$saveData[$key]['Tag']['title'] = $value;
$saveData[$key]['Tag']['slug'] = Inflector::slug($value);
}
if(!empty($saveData))$this->saveAll($saveData);
# this save all the tags
# now save data in tag_posts
$listOfExistingTags = $this->find('list',
array('conditions' =>array('title' => $tags),
'fields'=>array('id','title'),
'recursive' => -1));
$i = 0;
foreach($listOfExistingTags as $key=>$value){
$tagPostData[$i]['TagPost']['tag_id'] = $key;
$tagPostData[$i]['TagPost']['post_id'] = $postId; $i++;
}
if(!empty($tagPostData)){
App::import('model','TagPost');
$TagPost = new TagPost();
$TagPost->saveAll($tagPostData);
}
}
Any ideas on how to refactor this?
Use the CakeDC Tags plugin. It is unit tested and easy to throw in, takes ~15mins. See it's readme.md. Its basically just adding the behavior and adding a field "tags" to your form.

Outputting categories authors have written in as a class (WordPress)

OK, I have a very specific question that I hope someone can shed some light on.
I have a page that lists authors outputting using the following code
<?php
$display_admins = false;
$order_by = 'post_count'; // 'nicename', 'email', 'url', 'registered', 'display_name', or 'post_count'
$role = ''; // 'subscriber', 'contributor', 'editor', 'author' - leave blank for 'all'
$hide_empty = true; // hides authors with zero posts
if(!empty($display_admins)) {
$blogusers = get_users('orderby='.$order_by.'&role='.$role);
} else {
$admins = get_users('role=administrator');
$exclude = array();
foreach($admins as $ad) {
$exclude[] = $ad->ID;
}
$exclude = implode(',', $exclude);
$blogusers = get_users('exclude='.$exclude.'&orderby='.$order_by.'&role='.$role.'&order='.'DESC');
}
$authors = array();
foreach ($blogusers as $bloguser) {
$user = get_userdata($bloguser->ID);
if(!empty($hide_empty)) {
$numposts = count_user_posts($user->ID);
if($numposts < 1) continue;
}
$authors[] = (array) $user;
}
echo '<ul class="contributors">';
foreach($authors as $author) {
$display_name = $author['data']->display_name;
$avatar = get_wp_user_avatar($author['ID'], 'medium');
$author_profile_url = get_author_posts_url($author['ID']);
$filter = get_userdata($author['ID'])->yim;
echo '<li><div class="home ', $filter,' "><div class="feature-image">', $avatar , '</div>
<div class="post-title"><h3>', $display_name, '</h3></div>
</div>
</li>';
}
echo '</ul>';
?>
(I got this from another support topic and tweaked it, although I can't remember where)
At the moment, the $filter variable is just a string I enter in the 'Yahoo IM' profile box (a dirty fix to test the filter). I'd like this to actually be a list of the categories (as slugs that I will output in to the class="" part of the loop) that the author has posted in.
I essentially want to be able to filter the authors by category that they have posted in, and the filter I'm using (Isotope) operates using the class, so outputting the categories in to the class of the markup is what I'm after.
Any suggestions gratefully received!
// Returns the posts made by the author
$authorPosts = get_posts("author={$author['ID']}");
$categoryList = array(); // reset previous values
foreach ($authorPosts as $post) {
$postCategories = get_the_category($post->ID);
// Add to the categories the author has posted in
foreach ($postCategories as $category)
$categoryList[] = $category->slug;
}
// Removes duplicate categories
$categoryList = array_unique($categoryList);
You can then use $filter = implode(' ', $categoryList); and add it to your html.
RE not storing the array from the other answer, you can just echo out the slugs there and then like this:
$authorPosts = get_posts("author={$author['ID']}");
foreach ($authorPosts as $post) {
$postCategories = get_the_category($post->ID);
// Add to the categories the author has posted in
foreach ($postCategories as $category)
echo($category->slug);
}
otherwise if you want to put your PHP at the top and echo out the slugs further down the page pop there where ever you want to echo them:
$i = 0;
foreach($categoryList as $category) {
echo($categoryList[$i]);
$i++;
}

How to access array computer by a function within Codeigniter?

I have a function as follow:
function get_employee_information()
{
$this->db
->select('id, name');
$query = $this->db->get('sales_people');
$employee_names = array();
$employee_ids = array();
foreach ($query->result() as $row) {
$employee_names[$row->id] = $row->name;
$employee_ids[] = $row->id;
}
}
I'm trying to access this data from within an output to template, like this:
$this->get_employee_information();
$output = $this->template->write_view('main', 'records', array(
'employee_names' => $employee_names,
'employee_ids' => $employee_ids,
), false);
Yet this isn't displaying anything. I feel like this is something small and I should know better. When I tun print_r($arrayname) on either array WITHIN the function, I get the suspected array values. When I print_r OUTSIDE of the function, it returns nothing.
Your function is not returning anything. Add the return shown below.
function get_employee_information()
{
$this->db->select('id, name');
$query = $this->db->get('sales_people');
$employee_names = array();
$employee_ids = array();
foreach ($query->result() as $row) {
$employee_names[$row->id] = $row->name;
$employee_ids[] = $row->id;
}
return array(
'employee_names'=>$employee_names,
'employee_ids'=>$employee_ids,
);
}
You are not setting the return value of the function to a variable
$employee_info = $this->get_employee_information();
$output =
$this->template->write_view(
'main', 'records',
array(
'employee_names' => $employee_info['employee_names'],
'employee_ids' => $employee_info['employee_ids'],
),
false
);

Adding values to act as breaks in array_merge dropdown

I have three arrays getting different post types, which are then merged for a drop down in the Wordpress admin. I'm trying to insert empty values/breaks to make the drop down easier to read.
Here are the arrays and the array_merge:
// creating an array of pages
$featpages = array();
$pages = get_pages();
$pages[""] = "";
foreach ($pages as $page) {
$featpages[ $page->post_title ] = $page->ID;
}
// creating an array of posts
$postargs = array('numberposts' => 0);
$featposts = array();
$posts = get_posts($postargs);
$posts[""] = "";
foreach ($posts as $post) {
$featposts[ $post->post_title ] = $post->ID;
}
// creating an array of activities
$actargs = array('post_type' => 'activity', 'numberposts' => 0);
$featacts = array();
$acts = get_posts($actargs);
$acts[""] = "";
foreach ($acts as $act) {
$featacts[ $act->post_title ] = $act->ID;
}
// creating a combined array of pages and tours
$links = array_merge((array)$featpages, (array)$featacts, (array)$featposts);
I was hoping the [""] = "";for each one would add an empty row between each set, but it only works for one - I guess because they look the same to the array_merge?
[""] = ""; will overwrite the next one
Use [] = ''; instead

Categories