Call a function in function.php Wordpress - php

I'm studying PHP and have a basic question,
I have this code in the page portfolio.php
<?php
$args = array(
'post_type' => 'portfolio',
'orderby' => 'menu_order',
'order' => 'ASC',
'posts_per_page' => -1
);
$portfolio_query = new WP_Query($args);
if( $portfolio_query->have_posts() ) :
echo '<div id="primary" class="hfeed">';
while( $portfolio_query->have_posts() ) : $portfolio_query->the_post();
// project url
$portfolio_url = get_post_meta($post->ID, '_zilla_portfolio_project_url', true);
if( !empty($portfolio_url) )
$portfolio_button_copy = get_post_meta($post->ID, '_zilla_portfolio_project_url_copy', true);
?>
I would like to echo $portfolio_url in my function.php
Any reference for more study in this case would be appreciated.

It's not clear what you're trying to do, but if you need to pass a url to a function then you can do so with an argument:
function your_function($url) {
// Do whatever you want with $url here, like:
echo 'A link';
}
You can save the above into functions.php.
Based on your comments, I think what you're trying to do is take your code in portfolio.php and turn it into a function that you can call elsewhere. In that case you need to actually define it as a function:
function get_portfolio_url() {
// Insert your existing code in here...
// Then you can either echo $portfolio_url:
echo $portfolio_url;
// Or you can just return it if you plan on doing other things with it
return $portfolio_url
}
You can insert the above function into functions.php. Then you can call it anywhere with get_portfolio_url(). Technically you would no longer require portfolio.php, since you've created a function that does exactly the same thing. Be aware that you don't need to create separate PHP files for every function you require; you can just define them as separate functions in one location and then call them as necessary (which is essentially what functions.php is for in WordPress; a single file to hold all the functions your theme uses).

Related

Access the post data via short code (Visual Composer post grid)

I am using a Visual Composer (Post Grid) element, with a custom template.
I'd like to output the post id via a shortcode, so I've created a simple shortcode:
function myshortcode_title( ){
return get_the_ID();
}
add_shortcode( 'page_title', 'myshortcode_title' );
but it doesn't seem to retrieve the post ID. I am adding it to the grid via a Text block.
The shortcode works on any other page, but not inside the VC post grid.
How else can I access the post ID inside the post grid?
Thanks in advance! Here is a screenshot of the element.
I now it's late but I had the same problem and this answer can help other people.
You need to use the global $post in your function.
Exemple of usage:
function my_function_shortcode()
{
global $post; // important !
$args = array(
'post_type' => 'event',
'post_status' => 'publish',
);
$event_query = new WP_Query($args);
if ($event_query->have_posts()) : while ($event_query->have_posts()) : $event_query->the_post();
$event_location = get_post_meta($post->ID, 'event_location', true);
endwhile;
endif;
wp_reset_query();
}
add_shortcode('my_function_output', 'my_function_shortcode');

Wordpress Custom Function in Plugin to Return Post ID from Specified Category

Hoping you can help me figure out why I can't get get_first_post_in_category to successfully return a usable post ID. At the moment I am using the Wordpress Plugin Boilerplate to create a plugin that removes the first post of a specified category (through the admin options page) from the primary loop. All is well until I try and programmatically retrieve the post ID.
Here I define my hook (works fine):
// In private function define_public_hooks()
$this->loader->add_action( 'pre_get_posts', $plugin_public, 'exclude_featured_post_pre_injection');
Here is the callback function I am using to exclude a specific post from the main query. If $first_post_in_category_id is manually set, it works perfectly. If I try and set it to " = get_first_post_in_category();" I am thrown a 500 error.
public function exclude_featured_post_pre_injection($query){
// Doesn't work
$first_post_in_category_id = $this->get_first_post_in_category();
//Works
// $first_post_in_category_id = '427';
if ($query->is_home() && $query->is_main_query()) {
$query->set('post__not_in', array($first_post_in_category_id));
}
}
And here is the issue ::: this function I am attempting to just return the ID of the first post in the category to be used in other action/filter callbacks. If I call this, it returns a 500 error.
public function get_first_post_in_category(){
$cat_id = get_option('sticky_content_category_id');
// currently returns (string) '3' which has posts in it
$args = array(
'posts_per_page' => 1,
'cat' => $cat_id
);
$latest_cat_post = new WP_Query($args);
while ( $latest_cat_post->have_posts() ) : $latest_cat_post->the_post();
$first_post_id = the_ID();
endwhile;
wp_reset_postdata();
return $first_post_id;
}
Any idea on the best way to resolve the issues I am running into?
I cant see how it can cause an error 500 but the code below works for me.
$category_id = get_cat_ID('Wordpress');
//echo $category_id;
$args = array(
'posts_per_page' => 1,
'cat' => $category_id,
'orderby' => 'ID',
'order' => 'DESC'
);
$query = new WP_Query($args);
while($query->have_posts()):$query->the_post();
echo the_ID();
endwhile;

WordPress query_var by domain

I'd like to add a query variable to all queries coming from a certain domain.
For example, mydomain.com and proxydomain.com both show the same WordPress site, but for users visiting via proxydomain.com, I'd like to be able to handle their queries differently.
Additionally, I'd like to apply some different CSS styles for visitors coming through proxydomain.com.
I was thinking I could check for the query_var and apply classes based on the presence of that variable.
This is the code to add to your functions.php file:
add_filter( 'body_class', 'domain_as_body_class' );
function domain_as_body_class( $classes ) {
$classes[] = sanitize_title( $_SERVER['SERVER_NAME'] );
return $classes;
}
It adds the sanitized domain of your site (i.e. mydomain-com or proxydomain-com) as class of the body tag of your pages, so you can target the relative class for custom styles.
Update
For the queries you could add a function again in functions.php like:
function is_proxydomain() {
return 'proxydomain.com' == $_SERVER['SERVER_NAME'];
}
And then use it when needed on a query:
if( is_proxydomain() ) {
$args = array(
// arguments for proxydomain.com
);
} else {
$args = array(
// arguments for mydomain.com
);
}
$query = new WP_Query( $args );
I like the answer of d79 for the first part.
For the queries, I think it would be better to extend WP_Query class ( i.e. WP_Query_Custom ) and have one copy for each domain. Then you can load the file you need based on the domain in the functions.php file, and so you don't need to change in the future your calls everywhere you use WP_Query_Custom, even if you need to add more domains and different versions of WP_Query_Custom.
//in functions.php
$mydomain = str_replace('.', '_', $_SERVER['SERVER_NAME']);
require_once("path/to/my/classes/$mydomain/WP_Query_Custom.php");
//In each path/to/my/classes/$mydomain/WP_Query_Custom.php
class WP_Query_Custom extends WP_Query {
function __construct( $args = array() ) {
// Force these args
$args = array_merge( $args, array(
'post_type' => 'my_custom_post_type',
'posts_per_page' => -1, // Turn off paging
'no_found_rows' => true // Optimize query for no paging
) );
add_filter( 'posts_where', array( $this, 'posts_where' ) );
parent::__construct( $args );
// Make sure these filters don't affect any other queries
remove_filter( 'posts_where', array( $this, 'posts_where' ) );
}
function posts_where( $sql ) {
global $wpdb;
return $sql . " AND $wpdb->term_taxonomy.taxonomy = 'my_taxonomy'";
}
}
The example class is copied from extending WP_Query

Wordpress functions

So I have had a little search and maybe I am searching for the wrong thing. I am trying to run a function from my functions.php file in wordpress and assign the returned array to a variable.
When I run the function, it just echos out the returned data rather than assigning it to the variable.
I'm assuming this is a Wordpress thing.
Code from functions.php
function get_portfolioBlock( ) {
$portfolio_query = new WP_Query(array('post_type' => 'portfolio', 'posts_per_page' => 1, 'name' => 'test1'));
if ( $portfolio_query->have_posts() ) {
while ($portfolio_query->have_posts() ) {
$portfolio_query->the_post();
$portfolio_block = array('title' => the_title(), 'excerpt' => the_excerpt() );
}
return $portfolio_block;
} else {
return 'error';
}
}
The code in my template file
<?php $portfolio = get_portfolioBlock(); ?>
When the page loads it automatically loads the data into the page without assigning the variable for me to use else where
Thank you Gerald!
The reason for it echoing in out the function was because when I was assigning the_title and the_excerpt I should have been using
get_the_title() and get_the_excerpt()

Redirect Wordpress User to their own Post on Front-End Login

I'm trying to make the front-end login for Wordpress redirect to the post (in a custom post type) that was automatically created when they registered.
I can get the URL I want to redirect them with a wp_query. I imagine this is not the best way to do it, but I don't know enough php to figure it out. Here's my current attempt, but it just prints the url (the right one, at least!) on a blank page with the same login url they were already at:
function my_login_redirect( $redirect_to, $request, $user ){
global $user, $post;
$args = array(
'author' => $current_user->ID,
'post_type' => 'course-providers',
'showposts' => 1,
'caller_get_posts' => 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<?php wp_redirect ( the_permalink () ); ?>
<?php
endwhile;
} else {
echo "This User Has no Profile";
}
}
add_filter("login_redirect", "my_login_redirect", 10, 3);
Also, I imagine I don't need the wp_redirect and that I should just be using the login_redirect filter itself, but again, I'm pretty lost right now and just taking lots of shots in the dark.
Thanks for the help, and let me know if there's additional info that would make this more helpful for others or easier to answer. Thanks!
I ended up using a template redirect to make this work. I assume there's technically a better way to do it, but it's loading extremely fast and doing exactly what I need it to.
So, now, when a user logs in it goes to a direct url- /profiles - and the template on that page is just a redirect. I used the ideas and some sample code from this smashing magazine post on random redirects to make it work.
Here's the function I used in my functions.php file for the template to make the redirect happen:
function profile_redirect() {
// This is a template redirect
// Whenever someone goes to /profile (or any page using the profile template)
// this function gets run
if ( is_user_logged_in() ) {
global $current_user, $post;
$args = array(
'author' => $current_user->ID,
'post_type' => 'profile',
'posts_per_page' => 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ( $my_query->have_posts() )
$my_query->the_post();
//We have a post! Send them to their profile post.
wp_redirect ( get_permalink () );
exit;
} else {
// If there are no posts, send them to the homepage
wp_redirect ( get_bloginfo('url') );
exit;
}
wp_reset_query();
} else {
// If they're not logged in, send them to the homepage
wp_redirect ( get_bloginfo('url') );
exit;
}
}
Then, on my profile template, I put this at the top with the opening php tag to run the function:
profile_redirect(); ?>
This is working for me, so I'll leave it as is for now :)

Categories