INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
AJAX Load more start with x posts
I'm using Ajax Load more plugin.
I have made it to load X posts on button click, but on the page load there are no posts loaded initially (obviously).
What should I do to have (let's say) 10 posts loaded automatically and then next ones loading only on button click.
The code right now for that is :
echo do_shortcode('
[ajax_load_more category="'.$category->slug.'"
posts_per_page="10"
pause="true"
scroll="false"
button_label="Load articles"
button_loading_label="Loading..."]'
);
Do I have to code that functionality on my own or there is some way to achieve that just with the shortcode change?! | You need to set the `offset` in the query.
To get the right offset value, you will need to store and send back the offset value to your ajax script (`data-offset` in the input or an hidden field).
$args = array(
'posts_per_page'=> 10,
'post_status'=> 'publish',
'offset'=> $_POST['offset']
);
`$_POST['offset']` is coming from your button with a js script. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, ajax"
} |
Custom Post types and Custom fields in Multisite
I'm new to Wordpress Multisite and I wonder if its possible to define a set of Custom Post Types (Films, Categories and Actors) and a set of Custom Fields (i.e. a Film has a trailer field, actors and a category) for every new site a make for the network.
I need to be able to create new sites and all of them must come preconfigured with the CPT and CF I said.
Is it possible with Wordpress MU or should I find another solution? | If you place the CPT and fields code in a theme, each site in the network would be required to use that theme for the post type and custom fields to be available. If, however, you place that code in a plugin and network activate the plugin, every site in your network can use a different theme and retain the custom post type and custom fields you require. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "multisite"
} |
How to edit comments form on posts?
I have an old theme installed
There's **a text under the text area for comments** I would like to edit/delete
Already tried in _settings-->discussions_ and _comments.php_ to find that text
Looked also between plugin.
Where could I watch at now? | Check your theme, if it uses template, create a child theme and edit it. If it's not a part of comment template, edit another part.
You can try to find correct place with PsPad, Visual Code Studio or whatever else code editor while typing the phrase and searching in the template/plugin files.
If you need to hide it, use CSS (add `display:none`). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "comment form"
} |
Add a custom class to nav li item
It could look like a possible duplicate, but I have tried a plenty of solutions, and none of them has worked. The very last any basic one:
function kbnt_special_nav_class( $classes, $item ){
$classes[] = "special-class";
return $classes;
}
add_filter('nav_menu_css_class' , 'kbnt_special_nav_class' , 10 , 2);
And my nav call:
wp_nav_menu( array( 'theme_location' => 'header-menu', 'menu_class' => 'navigationList', 'container' => 'ul') );
`Ul` gets the correct class. However, the `li` items still have `page_item` classes and nothing else. Why? I have spent 30 minutes on this issue and still haven't found why. Thanks a lot in advance! | You code is working for me with (and without) some modifications on your code, to place in functions.php :
add_filter( 'nav_menu_css_class', 'menu_item_classes', 10, 4 );
function menu_item_classes( $classes, $item, $args, $depth ) {
unset($classes);
$classes[] = 'current-menu-ancestor';
return $classes;
}
If it's still not working, verify that your are working on the right theme_location id in wp_nav_menu().
Hope it helps ! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "menus"
} |
get $post (object,parts/values) in meta-box
I want to know, how to get i.e. $post ID, TITLE and etc.. in metabox?
is other solution available, instead of `$GLOBALS['post']` ? | Do not rely on globals like `get_the_ID()` or `get_post()` do. Use the parameters for your callbacks.
You get the current post object **twice** :
1. When you register the metabox, you get the post object as a second parameter.
2. When your output callback is called, you get it as the first parameter.
Here is an example showing both cases:
add_action( 'add_meta_boxes', function( $post_type, \WP_Post $post ) {
add_meta_box(
'test', // handle
'Box title', // title
function( \WP_Post $post ) { // output
print get_the_title( $post );
});
}); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "metabox"
} |
Does WP get all post_meta on POST page?
If someone opens any post at the front-end, does it matter how many times I call `get_post_meta` function? I thought it could increase performance if I won't call that function 2-3 times instead of 20 calls on single post page. | One call to `get_post_meta()` fetches all met keys and values for that post. All these values are then stored in the cache. The next call will just fetch the data from the cache. So you can safely call that function multiple times.
In details:
1. `get_post_meta()` calls `get_metadata('post', $post_id, $key, $single);`
2. `get_metadata()` checks the cache and calls `update_meta_cache()` if it doesn't find an existing cache.
3. `update_meta_cache()` fetches all entries with:
"SELECT $column, meta_key, meta_value
FROM $table
WHERE $column IN ($id_list)
ORDER BY $id_column ASC"
The same is true for user meta values. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "posts, post meta"
} |
What is the best practice for escaping data URIs?
Usually, you would use `esc_url()` to escape a URL before displaying it. If that 'URL' is a data URI (eg. `'data:image/svg+xml;base64,...'`), it will be trimmed blank by `esc_url()`.
The Codex page on Data Validation has this to say about escaping URLs:
> Always use esc_url when sanitizing URLs (in text nodes, attribute nodes or anywhere else). Rejects URLs that do not have one of the provided whitelisted protocols (defaulting to http, https, ftp, ftps, mailto, news, irc, gopher, nntp, feed, and telnet), eliminates invalid characters, and removes dangerous characters. Replaces clean_url() which was deprecated in 3.0.
Data URIs aren't covered by this function and don't appear to be covered by any of the other standard WP escaping functions.
Is there an established best practice in WordPress for escaping data URIs? | It is possible to pass an array with allowed protocols to the esc_url() function. For data-URLs this has to contain the `data` scheme, as this is not whitelisted by wp_allowed_protocols() as default.
esc_url( $data_url, array( 'data' ) ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "php, urls, validation"
} |
WP-Cron system broken
None of my cron events fire. I have deactivated all plugins on the site, and I made sure that I have not disabled wp-cron in the config file. I use AWS for hosting.
Any suggestions on how to fix this?
I have re-enabled one plugin to test cron issues - WP-Cron Events
The plugin generates a table populated with all cron events. Also, there is a error message that is generated that you can see in the screenshot I have attached.
 which caused the wp-cron.php file to give the 404... Fixed the permissions and now the warning is gone. This file gives a 200 code now, and cron jobs finally started to run again.
Maybe the 401 that you are receiving is caused by permissions issues on this file as well? | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp cron"
} |
Creating a button from data from Author meta
I'm creating an author box for every WordPress post, and I'm trying to pull a link from the author meta.
This code works fine, and prints the (however unclickable) URL but I want to compile this into a clickable button like "Follow on Snapchat".
Can someone give me a push in the right direction?
<?php
$snapchat_profile = get_the_author_meta( 'snapchat_profile' );
if ( $snapchat_profile && $snapchat_profile != '' ) {
echo '<a href="' . esc_url( the_author_meta('snapchat_profile')) . '"></a>';
}
?> | You just created an empty link, it has correct link but no inner text:
echo '<a href="' . esc_url( the_author_meta('snapchat_profile')) . '">Follow on Snapchat</a>';
And since you already stored the link in `$snapchat_profile` variable, no need to call the `the_author_meta('snapchat_profile')` function once again (it will only reduce in a few bits of extra memory usage and ..) so you should end up with this:
$snapchat_profile = get_the_author_meta( 'snapchat_profile' );
if ( $snapchat_profile ) {
echo '<a href="' . esc_url( $snapchat_profile ) . '">Follow on Snapchat</a>';
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "author, user meta"
} |
Style.css in child theme is loaded before Bootstrap
When I enqueue Bootstrap with `wp_enqueue_style()`, Bootstrap is loaded after the child theme's `style.css` and will override `style.css`. One way to load `style.css` after Bootstrap is to enqueue `style.css` as well, but this will cause it to be loaded twice. Any idea how to enqueue `style.css` once AND after Bootstrap? Thanks! | Mostly the parent theme might be enqueing the child theme's `style.css`, if so you can dequeue it by using handle and then enqueue with proper dependency.
If the child theme's handle is `child-theme-style`, then dequeue it using
`wp_dequeue_style('child-theme-style')`
then enqueue it as needed like so.
wp_enqueue_style('child-theme-dep',get_stylesheet_uri(),array('bootstrap-handle-here'))
. I think I need to add something in the twentysixteen child theme css file, but cannot work out what....something about the .entry-attachment?? I've tried various things to no avail.....
this is the page: < | Add these 2 lines to your css file in your child theme. You can change the percentages to suit your needs. (I've provided a starting point of what I think looks pretty good)
//text size
.entry-footer {
width: 30% !important;
}
//picture size
.entry-content {
margin-left: 55% !important;
width: 30%!important;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "customization, images, css"
} |
PHP Notice - Custom Function
I am using this code:
function the_alt_title($title= '') {
$page = get_page_by_title($title);
if ($p = get_post_meta($page->ID, "_x_entry_alternate_index_title", true)) {
$title = $p;
}
return $title;
}
add_filter('the_title', 'the_alt_title', 10, 1);
In debug.log i get
PHP Notice: Trying to get property of non-object in /var/www/html/wp-content/themes/my-child/functions.php on this line:
if ($p = get_post_meta($page->ID, "_x_entry_alternate_index_title", true)) {
How could I fix this? | `$page = get_page_by_title($title)` \- this line is failing somewhere, so you should do a check on this to make sure it exists.
Like so:
function the_alt_title($title= '') {
$page = get_page_by_title($title);
if (!$page) {
return $title;
}
if ($p = get_post_meta($page->ID, "_x_entry_alternate_index_title", true)) {
$title = $p;
}
return $title;
}
add_filter('the_title', 'the_alt_title', 10, 1); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "debug"
} |
Generate <meta name="description" Using the page title + first sentence of body text
So what I'd like to do is generate a meta description like this one
<meta name="description" content="[post_title]Craftsman 3 in 1 tool set. [post_content]This is a sentence or a few words from the main content body text which was entered in the post or page description of item..."/>
The meta description would take the page title and a few words or a sentence from the main post content.
Currently no meta description is being generated as I can see. Could you recommend a way to work this in. I'd like to avoid using bloated plugins etc and it is not feasible to go through each post 1 by 1 and do this manually as there are thousands of posts and pages. | You can use `wp_head` action to add something to head section. You can change the output according your needs.
<?php
add_action('wp_head','add_meta_des');
function add_meta_des() {
if(is_single())
{
global $wp_query;
$post = $wp_query->post;
$page_id = $post->ID;
$page_object = get_page( $page_id );
$content = wp_trim_words($page_object->post_content,30);
$output="<meta name='description' content='".get_the_title()."--".$content."'/>";
echo $output;
}
}
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, headers, seo"
} |
WP_Query orderby date not working
I have a simple WP_Query to get a list of posts of co-author (taxonomy _author_ ) order by date, this is the query :
$username = get_the_author_meta( 'login', $author_id );
$args = array(
'post_type' => 'any',
'orderby' => 'date',
//'orderby' => 'post_date',
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'author',
'field' => 'name',
'terms' => $username
)
)
);
$query = new WP_Query( $args );
The result is always a list of posts ordering by date ASC... I have already search solution over internet without success... Any idea ?
Thanks a lot | This will definitely work....It worked for me...
$username = get_the_author_meta( 'login', $author_id );
$args = array(
'post_type' => 'any',
'orderby' => 'date',
'order' => 'DESC',
'suppress_filters' => true,
'tax_query' => array(
array(
'taxonomy' => 'author',
'field' => 'name',
'terms' => $username
)
)
);
$query = new WP_Query( $args ); | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 10,
"tags": "wp query, order, date"
} |
What is the best / efficient way to get WordPress content by post id and why?
I just wanted to get WordPress content by post id. I found the following three ways to get WordPress content by post id. (All the following ways I found on this site.)
Method 01:
$content_post = get_post($my_postid);
$content = $content_post->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
Method 02:
$content=get_post_field('post_content', $my_postid);
Method 03:
$content=apply_filters('the_content', get_post_field('post_content', $my_postid));
What is the best / efficient way from above there methods and why? | The methods you offer for comparison are pretty much the same, with minor API differences and whether `the_content` filters are applied.
Within the loop `get_the_content()` should typically be used, which properly handles split into pages and so on.
To retrieve raw content `get_post_field()` is generally suitable, but any further processing (such as `the_content` filters) heavily depends on specific _purpose_ of retrieving content and what you are going to do with it.
PS take note that many extensions out there are dumb and variously break on `the_content` filter executed outside of loop / more than once. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "posts, content"
} |
Query by date from custom field
I would like to get WordPress posts whose custom field date is in the future, but I have a problem getting correct results from this query:
$args = array(
'posts_per_page' => -1,
'post_type' => 'matches',
'meta_key' => 'date',
'compare' => '>=',
'meta_value' => '2016-11-12',
'type' => 'DATE'
);
All I get are posts where the date matches '2016-11-12', though I use **'compare' => '>=',** and even **'compare' => '>',** shows these very same results. I don't understand that at all! | There is an argument meta_compare. Use it for comparison.
$args = array(
'posts_per_page' => -1,
'post_type' => 'matches',
'meta_key' => 'date',
'meta_compare' => '>',
'meta_value' => '2016-11-12',
'type' => 'DATE'
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, meta query"
} |
Translate current_time
I have `current_time` in theme and it displays date like: `THURSDAY, NOVEMBER 10, 2016`. But I need to translate it to Persian. How can I do this? | Used `date_i18n` instead of `current_time`. For example:
echo date_i18n( 'Y. F j.', strtotime( get_the_time( "Y-m-d" ) ) ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "date, translation, date time, timezones"
} |
Site Address and WordPress Address settings when using a load balancer
I am installing my wordpress forum in two identical servers:
1. InstanceA (public dns: instancea.com)
2. InstanceB (public dns: instanceb.com)
I would like to have both of these servers sit behind a load balancer:
LB (public dns: lb.com)
When filling in the Site Address and WordPress Address settings in `wp-admin->settings`, which address would I fill for each server?
I would like to use each instance's respective address for these fields. But this causes my load balancer to do a redirect (`301`) to the instance's address (eg: instancea.com).
Thank you. | When they say "where core files reside" they are referring to the url where they can be reached. Since you're using a load balancer, you want those requests to be split across both your servers.
To configure Wordpress in a load balanced environment, you need to configure a couple of settings. I like to do this directly in the DB since doing them 1 at a time through the gui will often prevent you from being access the other settings until they are all set.
In the `wp_options` table, set the following to the DNS address of your load balancer.
1. siteurl
2. home
Note, if your wordpress files are located in a sub-directory (e.g. `/wordpress`) then the `siteurl` should be set to the dns name of the load balancer followed by the path to the wordpress directory.
Keep in mind, you will also have to mirror your wp-content directory between your servers somehow. Some people will use some kind of cloud file storage for this (e.g. AWS S3), but there are other ways as well. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "redirect, options, wp config, site url"
} |
Order WP_Query by multiple fields, subtracting them from one another
I have two custom fields for each post, `vote_up` and `vote_down`.
I know how to order by one of them, but I'm wondering how I can get the totals of both, subtract `vote_down` from `vote_up` and then display them according to the result of that calculation.
Ideas? | Per Rarst's request, as an answer instead of comment :-):
The easiest way might be to create a third custom field, vote_diff, and order by that. You could use `update_post_meta` in a function to automatically calculate/enter the value of vote_diff when vote_up or vote_down changes. Where & how to do that will depend on where/how vote_up and vote_down are currently added/updated (plugin or theme or ....?). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wp query, order"
} |
How to reset wordpress but not plugins and settings
How to mass delete all posts with tags & comments but not plugins. There are some plugins but, Is there any plugin available which deletes all data related to posts like tags, comments etc.?
Is it possible in wordpress? | If you're looking to delete posts, categories, tags, photos, media, EVERYTHING. just clear the database entirely. Plugins will recreate their db entries if they need them.
Go into phpmyadmin and find the right database, then in content, select all of the tables and drop them. You don't want to delete the actual table though.
Now next time you go to your site, You'll start over fresh at the wordpress install area.
WARNING. IF YOU HAVE A CUSTOM THEME. THis will delete your theme settings so you may want to back them up in the theme control panel before doing this. This will not delete the actual media in your install, so you'll still have pictures in your wp-content/uploads folder.
IF YOU DON"T want to do that, you can always try this plugin: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, plugin development"
} |
Possible?? Pull Plugin Property Data to a Theme's Custom Post Type
I bought a real estate theme and want to use the property listing data that I get from a paid plugin.
The plugin listing data is clean, and stored in the WP database.
The theme uses custom post types so I'm trying to bridge my plugin data to the theme.
Thanks! | I'm putting this in as an "answer" just to give you pointers on where to start. Once you have specific questions concerning code you'll probably want to ask new questions.
First, I'd create a child theme. (Look on Google, there are tons of examples/tutorials on how to do that.)
In your child theme, create template files for the relevant custom post type. (I'd copy the archive.php and single.php files from your parent theme into your child theme, then edit the filenames.) Typically these would be named archive-CUSTOM_POST_TYPE_NAME.php and single-CUSTOM_POST_TYPE_NAME.php.
On those two template files you should be able to reference/display the custom fields created by the plugin using `get_post_meta()`.
If all works as expected, voila and hooray! But there may be challenges depending on how the plugin is written and how it stores the information, so be sure to check back with the plugin creator and us before it drives you crazy. :) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, plugin recommendation"
} |
Is it possible to use % sign in post permalinks?
While working on a client site which is based on deals and offers I found that whenever I am using % sign in the title of the post, it gets removed from permalink.
After doing some research, I found that wordpress removes it automatically to make the URL search friendly. Some people suggested using "percentage" instead of % sign. I believe that using percent word on a deals website is quite awkward.
Is there is any other way to make it possible to use % sign without damaging the SEO of the website? Do you guys think that if I use % sign in the title and permalink removes it, then it will hurt the SEO?
Many PHP websites (not wordpress) which are already using % sign are doing great in Search rankings. How are they making it possible? | Just answering to close out the question, but if anyone has other opinions please chime in.
No, it's not possible to use % signs in post permalinks without some very hackish workarounds. It's also not advisable given they are used in URLs as special characters. That said, the lack of % symbols in the permalink should not adversely affect SEO as Google and other search engines will already be filtering them out. If you want, edit the post-permalink/slug to use "percent" instead, which Google will understand. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, seo"
} |
is there a specific place where add_filter must be placed?
Most plugins mention adding add_filter to functions.php, but can I use it elsewhere? Does it depend on the plugin?
I am trying to use add_filter in a custom template file before get_header(); but it doesn't look like its being added on time.
I guess I am trying to figure out the order of when things run, so that I can call it at a point where it's available. | add_filter() and add_action() are available before any plugin is loaded. So you can use both in the first line of your plugin or theme.
For readability I recommend to group action and filter registrations at the very top of your main file:
in a plugin, the file with the plugin header in a theme the functions.php There are exceptions for that rule:
Chained callbacks. In this example I register an action for shutdown only when the first filter for wp_nav_menu_objects has been called. So the second callback cannot be registered at the same time as the first one.
to conclude it is possible to a certain point but it's not recommanded | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "filters"
} |
Best approach to serve static content within a regular page
I am developing a wordpress plugin which is supposed to display static forms to the front end users. These forms will be protected by another plugin managing user logins/registrations on page level.
My content should therefore be managed within a regular wordpress page. My content will then be the only thing displayed in the content section of that page. What is the best design approach for my plugin to insert that content?
Shortcodes would be an option, but I think they are not meant to be used for this as my content should not be inbetween other content but standalone. | You can use `the_content` filter to override page content and output whatever you want. Conditional Tags can help restrict your filter to running on specific pages. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, customization, pages, design"
} |
Can I install a new Wordpress site inside a sub-directory of an existing Wordpress site?
One of my clients has very limited resource. His current Wordpress site is installed at via FTP at `/public_html`:
We need to show him a UAT site before replacing the existing site. In the past, we used to create a new site elsewhere and replace an existing site when UAT is passed. This particular client is using a FTP hosting service with specific environment. So we want to play safe and create the UAT site in the same hosting environment.
So, it it possible to install a new separate Wordpress site in a sub-directory of the existing site, i.e.:
and hopefully his old site still runs well during the UAT period.
Since he has only FTP and phpMyadmin access, can I just copy a new Wordpress source to `/public_html/uat` and setup there? | Yes, you can do that. It won't affect any of the installation. I have already done this for few sites. Works without issue. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "directory, installation, ftp"
} |
jQuery selectable() function won't work in wordpress
I have this script in a wordpress website
<script>
jQuery( function($) {
jQuery( "#selectable" ).selectable();
} );
</script>
All my other scripts work but with this I got TypeError: $(...).selectable is not a function(…). When I use it without wordpress it works perfectly. | I always refer to to this blogpost about how to including jQuery code in WordPress. It shows you how to use noConflict within your javascript-code.
var $j = jQuery.noConflict();
$j(function(){
// YOUR CODE HERE
}
}
Also make sure that the jQuery library is included on the frontside of your WordPress installation with the wp_enqueue_script-function. Hope it will work out for you. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery, javascript"
} |
How do i allow access to a single file in my root directory?
I want to register my website (which is a wordpress site) with the google webmaster search console. This requires me to upload a verification html, but access to that is prohibited by the rules in htaccess which wordpress sets. Is there an easy workaround for this? I'm not that familiar with .htaccess, but i have ssh access to it and can change it if you tell me what needs to be changed. | I'm not aware of any such rule set by WordPress. If I create a file generic.html in my root WP folder and then go to www.mypage.com/generic.html the file will open.
What exactly happens when you put the file into your root folder (next to wp-config.php)?
In any case, if there are rules in .htaccess that are causing some form of redirect or denial you could just remove those for a few minutes while Google pokes at your page to check for the file. The check only needs to happen once after all.
An alternative is if you already have the page in your Google Analytics account you can choose "Alternate methods" on the Webmaster Tools screen that tells you to upload the .html file and that will just prove your ownership from your Google Analytics account. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "htaccess"
} |
Sending email with wp_email and AJAX
New to WP and PHP:
I'm trying to send an email with AJAX. My wp_mail is returning true and I'm receiving no errors on GoDaddy where I'm hosting, but the email is never actually received. Here's my php function :
add_action("wp_ajax_send_email", "send_email");
add_action("wp_ajax_nopriv_send_email", "send_email");
function send_email() {
$to = "[email protected]";
$subject = "Hey";
$message = "Hello";
$headers = "From: [email protected]";
if (wp_mail($to, $subject, $message, $headers)) {
echo json_encode(array('status' => 'success', 'message' => 'Contact message sent.'));
exit;
} else {
echo json_encode(error_get_last());
}
}
I do recieve the success message in my JS. | Have you tried without the ajax? Is that where you're actually sending the mail? Try just putting the wp_mail function right under headers and see if you get the mail.
Also i agree with theDeadmedic. It could be spam. Check the google spam folder and if its' not there, try sending to an email on your own domain (as long as it's not using googles servers) Also, I always add content-type to my header to help reduce the spam flag. It may help you:
$headers = array('Content-Type: text/html; charset=UTF-8');
$headers[] = 'From: CMCENTERS <[email protected]>'; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "ajax, email, wp mail"
} |
How can i remove JUST the title tag from wp_head() function?
i'm using wordpress 4.6 i'd like to remove just the title tag automatically outputted by wordpress because need to hardcode the html title tag in the template.
i guess is something like this:
add_action('wp_head', '//remove title tag command');
but i didn't find any valid solution so far. | You can see everything added to `wp_head` in the file `/wp-includes/default-filters.php`.
If your theme supports the title tag, you can remove it entirely with `remove_action`:
remove_action( 'wp_head', '_wp_render_title_tag', 1 );
Though it may be simpler/better to use `remove_theme_support( 'title-tag' )` in a child theme, which is what `_wp_render_title_tag` checks before outputting the title tag. | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 2,
"tags": "title, wp head, wp title"
} |
Which php file lists all the post of a category
In my primary menu, I have added a category "News & Events" and when I click this page, I get all the posts of this category. Which `php` file I have to edit, in order to change some things that I don't want to appear when the posts are listed in that page? | WordPress uses a hierarchy of templates (see the visual overview) which it checks for presence. In your case when showing a category archive it will check for presence the following files in this order and use the first one it finds:
* category-$slug.php (In your case probably category-news-events.php)
* category-$id.php
* category.php
* archive.php
* [paged.php] if paged
* index.php
So if you want to change things for a specific category, you best create a `category-$slug.php` (copy from `category.php`). If you want to to modify the general presentation of categories modify `category.php` directly. If `category.php` is not present, just use the next existing file according to the hierarchy. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "categories, templates, template hierarchy, archive template"
} |
Is Twenty Eleven Theme Responsive ? any update?
Someone asked me to make his site theme mobile friendly, and he gave me his theme which is Twenty Eleven theme. I want to know is this theme mobile friendly at all of has some bugs on mobile displays ? Also is any recent updates to this theme, or will be in near future ? because I want to know if I want to make it responsive, should I make my changes as a child theme ? what’s the best way to change the source code of this theme ?
Thanks in advance. | > Is this theme mobile friendly at all of has some bugs on mobile displays?
Go and preview the theme on your mobile device to find out if it's friendly or not - wordpress.org/themes/twentyeleven. You can also use a service like BrowserStack to test in various browsers and testmysite.thinkwithgoogle.com to get a score for UX.
> Any recent updates to this theme, or will be in near future?
Trac show this theme was update in the last 3 months - Last updated: August 15, 2016 - themes.trac.wordpress.org/browser/twentyeleven/
> If I want to make it responsive, should I make my changes as a child theme? what’s the best way to change the source code of this theme?
Read up on creating child themes - codex.wordpress.org/Child_Themes | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "responsive, theme twenty eleven"
} |
Extending Genericons in WordPress
With wordpress 4+, is it possible to create our own genericons and add them to the existing list that is bundled with WordPress? I know exactly what I want, which I can design in illustrator, but the default icons with the CMS don't come close to it. If so, is there a tutorial online?
I'd rather go this route than adding on an addition large font system along with genericons.
Thanks | You need something like Fontastic or Grunticon to create your custom fonts/icons.
Then just add your fonts to your html with `wp_enqueue_style()` or add the head elements directly.
There is a section on the Genericons GitHub that describes Building your own Genericons using FontCustom or Fontello. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "icon"
} |
how to import a custom website into Wordpress
I've decided to try out Wordpress for the first time, so apologies if this is a nooby question. I want to try and make a basic template website, based on something that was already provided. I currently have a local static website (html, css & js files) and would like to import this into Wordpress so I can manage my content through them. Is there any way to do this? | There is documentation on how to create a theme on the codex: Theme Development.
You can also get started quickly with basic starter themes; _underscores_.
There are also tools that you can use to package and distribute your theme; `wp dist-archive` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "import, static website"
} |
Remove from a div by class name from post page if post author role is not administrator
I have a site with two type of user role, administrator and author.
I have a dive class name "site-shop-wrapper" which I want to show only to posts added by the administrator and hide it for all other posts added by authors.
So basically I need a function to check the post author role and if it was not an administrator, then remove the div by class name.
I am new to WP and don't know much about it, any help with bee appreciated. | Finally, I decided to use if author_can function. However, I believe there is a better way of doing this. `add_action('wp_footer', 'remove_buybutton_from_non_admin'); function remove_buybutton_from_non_admin(){ if (author_can($post->ID, 'activate_plugins')) { ?> <script> var appBanners = document.getElementsByClassName('shop-wrapper'), i; for (i = 0; i < appBanners.length; i += 1) { appBanners[i].style.visibility="show"; } </script> <?php } else { ?> <script> var appBanners = document.getElementsByClassName('shop-wrapper'), i; for (i = 0; i < appBanners.length; i += 1) { appBanners[i].style.visibility="hidden"; } </script> <?php } }` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, functions, javascript, user roles"
} |
No plugin updates after moving wp-config.php above root map
After moving **wp-config.php** to a higher map then the root I get this **error message** when an **update** is started of **a plugin**.
Everything is working properly on the site only updates generates now errors,
How can I solve this so updating still runs without errors and without to move "wp-config.php" to root map back?
> Warning: unlink(/home/debxxx/security/domain/wp-content/uploads/updraftplus.1.12.25-YS3ytg.tmp): No such file or directory in /home/deb9xxx/domains/domain.com/public_html/wp-admin/includes/file.php on line 505
>
> An error occurred while updating UpdraftPlus - Backup/Restore: Download failed. Destination directory for file streaming does not exist or is not writable. | I guess ABSPATH defined in wp-config.php file now pointing not to root directory and that plugin trying to use this | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "plugins, updates, wp config"
} |
Add additional Fields for users and get value
I have register form where all users is subscribers in system, few fields is store in meta table in database, how i can get this user meta key in additionals field for each users? | Meta table? (wp_usermeta or wp_postmeta)?
You can get any meta of user by get_user_meta | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "user meta"
} |
Git ignore everything except custom theme directory
I only just started trying to use GitHub with WordPress, so I'm completely new to everything git.
My problem is simple: I want to setup my .gitignore so git ignores absolutely everything except my Wordpress theme which is located at a custom directory ' **/goods/themes/my-wordpress-theme** '.
I've tried a variety of .gitignore files such similar to the following and nothing works.
# Ignore everything
*
# Except 'my-wordpress-theme'
!goods/themes/my-wordpress-theme/*
I'm running Ubuntu with git version 2.7.4
Please help! Thanks, Asher. | Run ignore on your `themes` directory and check out your themes to their individual directories. That will keep your theme segmented just as your WordPress environment. There is no sense in checking out a root git for a single theme. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, git, github"
} |
Can't upload images on new theme
I am using underscores to create a new WordPress theme, the site is being hosted locally using MAMP. Whenever I try and upload a image either in a post or in the theme customization tab, this error is shown "An error occurred in the upload. Please try again later."
I have tried reinstalling WordPress but the issue prevails. Also if the theme is changed images upload perfectly.
Anyone know what might cause this, is there something missing in the underscores code that is creating this problem.
Thanks | That is a common Mac OSX issue – you need to adjust your file permission for the uploads folder. The problem with changing the permissions manually is your have to change them each time you create a new project, which is tiring.
You can give MAMP permission and you will never have to worry about the same problem again. Here are some instructions: <
Good luck. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, images, themes, uploads"
} |
Slider Thumbnail Size Issue
My website < features a slider on the front page and i'm having issues with the uniformity of its thumbnail sizes. Please, help me out.The slider thumbnail size in the function.php is 600*400. The left most thumbnail is true to the code. But the other two aren't.; ?>` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, post thumbnails, slideshow"
} |
How to get custom field image url of specific size
I have a "cmb2" custom field with `type->file`. and i use it to upload images.
**If i use:**
`echo get_post_meta( $post->ID, '_pf_photo1', 'medium' );`
i get the url of the full image (not the medium one).
How can i get the url of the 'medium' / 'thumbnail' and so on... | The `get_post_meta()` function can help to get the meta field but will not retrieve different size.
Assuming `_pf_photo1` embed the attachment id, you can do something like that:
// Note the "_id" suffix
$attachment_id = get_post_meta($post->ID, '_pf_photo1_id', true);
Last parameter for this function can not be 'medium',
Now,you can use `$attachment_id` with different function depending on what you really want to get (url, img element...):
$attachment_element = wp_get_attachment_image( $attachment_id, 'medium' );
echo $attachment_element;
There is more ways to get details for attachment `wp_get_attachment_url()`, `wp_get_attachment_image_src` (that returns an array with url, width, height).
You will find more details to discover these functions here
Hope it helps ! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "plugins, custom field, attachments, post meta"
} |
Understand post type
I am a bit lost, even after searching answers qutie everywhere.. I am creating a theme for Wordpress, and I would like to have three custom post types (gallery, audio and video). So I added the support into the theme:
add_theme_support( 'post-formats', array( 'gallery', 'video', 'audio' ) );
But then what? I can choose via a radio button when I create a post which one I want to use but where do I put the meta?
I want to display a video. where do I put the video URL? same for audio and gallery.
Is there an easy way to add control depending of the custom type? | You are confusing things a bit, these are post **formats** , not post **types**.
Formats are a native _taxonomy_ , not a post type. As any taxonomy its primary (and only) functionality is to organize posts in logical groups.
Formats don't do _anything_ on top of that. You need to implement yourself _any and all_ functionality you want your posts with Format assigned.
This takes custom code in your theme (often with some custom fields framework as helper). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "posts, theme development, post type"
} |
/wp-admin/ doesn't work but /admin/ does
When I try to login via domain.com/wp-admin/ it will not allow me to do so. However, when I log in via domain.com/admin/ it will allow me to login with no problems.
Does anyone have any ideas as to why this is? And possibly how to fix this?
Thanks in advance. | In general you can change where items link with WP Constants. But according to `get_admin_url()` it's possible the URL was filtered with `admin_url` in which case you might be able to add a filter with a high priority and override what is being sent. The default is;
$url = get_site_url($blog_id, 'wp-admin/', $scheme);
if ( $path && is_string( $path ) )
$url .= ltrim( $path, '/' );
return apply_filters( 'admin_url', $url, $path, $blog_id );
As stated before, you should check your installed plugins (mainly security plugins) or `.htaccess` for wild redirects. Try disabling all plugins to narrow down that aspect pretty quick. Be sure to check the `/wp-content/mu-plugins/` folder for auto-loaded plugins.
If you can, search your theme and plugins for any reference to `admin` as well as search your database for `admin` to see where it might be set. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp admin, login"
} |
How can I automatically send an email with an excel file containing submissions for a form rather than an email per submission?
I recently took over web admin for a nonprofit organization and one of the things they would like changed with their site is to have multiple forms such as contact, volunteer, donations, more info, etc. They would like this data sent in an email so that it can be sent to focus group members but need it sent in a daily/ weekly email rather than an email for each individual submission. I think that an excel file is the best way to accomplish what they want and I have looked at several form plugins but they only support manual export of excel files. Is there either a plugin that supports emailing excel files or is there another way I can automate an export and email that export? Thanks in advance! | Easiest way to accomplish what they were looking to do was to recreate and create new forms in Google Drive and then embed them into the page. This allowed there to be a live spreadsheet with responses that any admin could access. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, forms, email, csv"
} |
How to use a class within a cron job function
* I have cron jobs successfully working in WordPress,
* However, when I attempt to call a class from within the cron function it doesn't run.
* How would I call in a class with a cron job function?
* * *
add_action( 'hourly_event', 'hourly_function' );
function hourly_function() {
// This otherwise works when not within a cron job function
$newClass = new newClass();
$newClass->newClass_function($var1, $var2, $var3);
}
$newClass is declared within plugin.
* * *
require plugin_ROOT.'gd-text/Box.php';
require plugin_ROOT.'gd-text/Color.php';
require plugin_ROOT.'gd-text/HorizontalAlignment.php';
require plugin_ROOT.'gd-text/TextWrapping.php';
require plugin_ROOT.'gd-text/VerticalAlignment.php';
use GDText\Box;
use GDText\Color;
class newClass {
public function newClass_function($var1, $var2, $var3){
}
} | You're calling a function with variables that are not defined and are required for the function to work correctly.
function hourly_function() {
$newClass = new newClass();
$var1 = 'this should';
$var2 = 'work with';
$var3 = 'some content';
$newClass->newClass_function($var1, $var2, $var3);
}
You might want to move those variable to a `__construct`
if ( ! class_exists('AClass')) {
class AClass {
function __construct( $var1 = null, $var2 = null, $var3 = null ) {
//...
}
}
}
$instance = new AClass(1,2,3);
Or the `__invoke` method:
if ( ! class_exists('BClass')) {
class BClass {
function __invoke( $var1 = null, $var2 = null, $var3 = null ) {
//...
}
}
}
$instance = new BClass();
$instance(1,2,3); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "cron"
} |
WordPress Rest API response
Is it possible to return plain text in a WordPress Rest API response? By default this seems to return JSON. Any advice on the recommended way to override this? Doing a json_decode() on my response object before it is returned from the callback function does not have any effect, so I assume the JSON gets created after this.
Thanks! | You might be able to output your headers with the response. Then just kill the request with `exit();`.
The default is usually to return a value and let the process encode and output for you.
* * *
Based on <
function my_awesome_func( $data ) {
header("Content-Type: text/plain");
print_r( array('foo'=>'bar'));
exit();
}
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/test/', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
} ); | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 1,
"tags": "rest api"
} |
Track write actions to the database
Is there a single action or filter that is run when a
* post is updated
* option is updated
* user is updated
* plugin is updated
* any other content is updated and wrote to the database
?
I want to be able to track all the changes I made in my development environment and save them to a file so that I can then update my live database with these patches automatically.
Is this maybe the filter I'm looking for?: < or does anyone know of a hook that's better suited?
Or is there a plugin out there, that I haven't found yet, that does exactly this? | Seems like there's a plugin out there that does quite this!
It's VersionPress!
In this blog post is explained what they used to track all the complicated changes.
Instead of using the 'query' filter they use the option to create a db.php file in the wp-contents directory to extend $wpdb like explained in this post: wp-content/db.php : where is this file? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, filters, database, actions"
} |
url rewrite parsing a custom url parameter not working
For SEO purposes I want to add a few specific urls to act as aliases to the archive page for a custom post type archive page that I have.
Now the custom post type archive page optionally accepts GET parameters which I then do various things with if they are parsed.
Taking the example below from my functions.php file, the add_rewrite_rule() does work in so far as going to /test/url/ on my site does take me to the archive page for the custom post archive page. So the basic catch is definitely working as I don't get a 404 page.
However the get parameter (param1) doesn't appear to have made the rewrite. It's as if it wasn't defined.
function rewrite_test() {
add_rewrite_rule('^test/url/?', 'index.php?post_type=custom¶m1=value']), 'top');
}
}
add_action('init', 'rewrite_test');
So what is wrong with this, how can I get the custom url parameters I want parsed via the rewrite rule? | You'll need to append the new variable (`param1`) to the public query variables:
add_filter("query_vars", function( $vars ){
$vars[] = 'param1';
return $vars;
});
Now you'll be able to get the value of this param with `get_query_var( 'param1' )`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "url rewriting, rewrite rules"
} |
Get terms from multiple taxonomies
I have to get all the terms from four taxonomies:
* vehicle_safely_features
* vehicle_exterior_features
* vehicle_interior_features
* vehicle_extras
I tried this:
$terms = get_terms( array(
'taxonomy' => 'vehicle_safely_features',
'vehicle_exterior_features',
'vehicle_interior_features',
'vehicle_extras'
) );
But, it only gets terms of `vehicle_safely_features` and not all of the taxonomies. | If you want to retrieve multiple taxonomies you need to put the four taxonomies in an array, you are doing this, but you have put `taxonomy=>` in the array.
$terms = get_terms(
'taxonomy' => array(
'vehicle_safely_features',
'vehicle_exterior_features',
'vehicle_interior_features',
'vehicle_extras')
);
Hope it helps | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 3,
"tags": "custom taxonomy, terms"
} |
Multiple postmeta values to the same post_id/meta_key combination?
I was diving in my Wordpress installation to start thinking in a future development and I did this query:
select * from postmeta where post_id = 1485433 and meta_key = 'qode_revolution-slider'
This query has as result 6 rows... identical, except for the meta_id value.
In fact, for test, I executed:
select post_id, meta_key, count(meta_id) as metas
from tpostmeta
where post_id > 0
group by post_id, meta_key
having metas > 1
order by post_id;
And I have several posts (more than 30) whit the same meta_key more than once... I have seen 2, 3, 6 and 8 times repeated some values...
Is it normal? I thought that each combination post_id/meta_key must be unique, and this was a wordpress core job..
Thanks you all, regards | No, it does not have to be unique. Whether it's a good practice to use it this way - that's another question you can ask that plugin authors. Here's the scenario:
* you have a slider in an entry
* slider has several slides
* each slide is stored as meta
In this case, you will have couple records with the same `post_ID` and same `meta_key` (let's call it 'slide'). You can fetch them with `get_post_meta( $post->ID, 'slide' )` into an array.
Personally, I would store all slides in a single meta as a serialized array. But I do see some use cases for storing repeatable data in separate meta records. For example, you might need to treat it `meta_value_num` in you meta_query, which will not work with serialized array data. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post meta, meta query"
} |
Reusable and site-wide content that can be used in a theme
**Goal:** To define content (phone number, address etc) in the admin area that can be used (called upon) in a theme.
**Context:** I am making a theme for a multi-site where every site will look the same, but have different content. The user should be able to easily add basic information in the admin area, preferably accessible through the left menu. The data fields will be predefined. _It is important that each piece of data can be fetch independently._
**My initial thoughts:** Making a simple plugin where the user can enter the information. I was thinking of putting it in the functions.php file, but was not sure what would happen to the data if I made a new theme in the future.
Are there other obvious ways of accomplishing this that I haven't thought of? Any suggestions to how I could solve this in a future proof way?
Also, recommendations for good resources on the topic is appreciated! | Using functions.php inside your theme will have the functionality only for that theme.
I think a simple approach will be to create a plugin or a mu-plugin as @Benoti is suggesting where you will create a settings page that will be saved on options table.
There are a few guides to create admin pages: <
There are also some ready made plugins like this ones: <
From all available options I think is best to create your own options page as it is not very complicated and make it as a mu-plugin so all sites in your network will have it without the need of activation. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, custom content"
} |
Image Galleries for website migrated from .com to .org
I've migrated a website from .com to .org with all of the content for a client. This client has a large amount of images that were previously arranged in various galleries on different pages. Some of these galleries where simply just a row with 4 or 5 images fit together, and some galleries where a large amount of images put together in a mosaic style pattern. I am trying to replicate this now that they are no longer using wp.com but I have been unable to find a plugin with the same functionality as they used to have on .com.
Is there a standard way of replicating .com functionality? Or is the plugin that is available to wp.com available to use after a site is migrated? | Jetpack is the open-source plugin maintained by Automattic that provides a large amount of WordPress.com functionality to self-hosted / .org sites.
Here's an article on tiled galleries, specifically. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, images, gallery, wordpress.com hosting"
} |
get csv of users with user_meta
i would like to export all users with user_metas.
Right now my sql looks like that
SELECT
u.ID,
u.user_email,
u.display_name,
um1.meta_value AS first_name,
um2.meta_value AS last_name,
um3.meta_value AS phone_number,
um4.meta_value AS salutation,um5.meta_value AS title
FROM wp_users u
LEFT JOIN wp_usermeta um1 ON u.ID = um1.user_id
LEFT JOIN wp_usermeta um2 ON u.ID = um2.user_id
LEFT JOIN wp_usermeta um3 ON u.ID = um3.user_id
LEFT JOIN wp_usermeta um4 ON u.ID = um4.user_id
LEFT JOIN wp_usermeta um5 ON u.ID = um5.user_id
WHERE um1.meta_key = 'first_name'
AND um2.meta_key = 'last_name'
AND um3.meta_key = 'phone_number'
AND um4.meta_key = 'salutation'
AND um5.meta_key = 'title'
The problem is I would like to get all user and not only those with the meta_keys specified above.
How would I do that? | SELECT
u.ID,
u.user_email,
u.display_name,
um1.meta_value AS first_name,
um2.meta_value AS last_name,
um3.meta_value AS phone_number,
um4.meta_value AS salutation,
um5.meta_value AS title
FROM wp_users u
LEFT JOIN wp_usermeta um1 ON u.ID = um1.user_id AND um1.meta_key = 'first_name'
LEFT JOIN wp_usermeta um2 ON u.ID = um2.user_id AND um2.meta_key = 'last_name'
LEFT JOIN wp_usermeta um3 ON u.ID = um3.user_id AND um3.meta_key = 'phone_number'
LEFT JOIN wp_usermeta um4 ON u.ID = um4.user_id AND um4.meta_key = 'salutation'
LEFT JOIN wp_usermeta um5 ON u.ID = um5.user_id AND um5.meta_key = 'title'
;
that's the right one. thanks jgraup for the hint | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "query, export, csv"
} |
PuTTY is glitching out when I try to install wordpress
I understand this is probably a pretty noob situation, but I can't for the life of me figure out why it's doing this.
Any ideas on how to overcome this so I can get WP installed on my server? I've tried searching around for an answer, but apparently nobody else has ran into this issue.
The command entered is:
curl -O
The output is a bunch of gobltygook on the screen. Expected output is downloading the zipped file. | Curl is outputting the response to the screen. You need to send the output to a file, like this:
curl -o wordpress.tar.gz
Note the lowercase 'o', and the presence of a filename after that argument. You can name the file whatever you want. With this exact command, it will be downloaded into whatever folder you are currently in. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "installation"
} |
Favorite websites with shortened hyperlinks
Suppose in the site there are frequent links to another website, always tree same, say Wikipedia. Is there a way to write links to Wikipedia in a shortened way, and tell wordpress to translate it?
Example: something like `[wiki]/geography` shorthand for `en.wikipedia.org/wiki/geography` | Sure, you're looking for the shortcode API. That would enable you to write a short piece of code that does exactly what you want. As easy as this in your `functions.php`:
function wpse246274_wiki( $atts ) {
$link = " . $atts['link'];
return $link;
}
add_shortcode( 'wikilink', 'wpse246274_wiki' );
Which you would use like this in your post:
<a href="[wikilink link='geography']">Geography</a>
You could even leave out the attribute and just use
<a href="[wikilink]geography">Geography</a>
But that doesn't look as elegant. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "shortcode, links"
} |
Query for posts from any post type but only add instock products
I need build a query like these :
Fetch 10 posts from any post_type but if the post_type was product then only add it if it is `instock`.
When i use meta_query for this purpose it only returns products ! because that meta is not available on other posts.
What can i do ?
Thanks. | You can check status `instock` only if meta key `_stock_status` exists.
Something like:
'meta_query' => array(
array(
'key' => '_stock_status',
'value' => 'instock',
'compare' => '=',
),
'relation' => 'OR',
array(
'key' => '_stock_status',
'value' => '',
'compare' => 'NOT EXISTS'
),
)
Note: Code is not tried or tested, so check for any syntax errors | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, wp query, post meta, woocommerce offtopic"
} |
Is it safe to include a javascript file in a template's php file?
I want to include some jquery plugin files to my wordpress multisite install. My solution involved creating a specific template file for the pages that required these jquery plugins. Below is the line of code that includes my javascript file which I have placed at the last line of the template file.
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/plugins/jquery.tablesorter.min.js" ></script>
Is this solution a safe way to include files in specific templates? Any feedback would be very helpful! | As @N00b mentioned Yes, it is safe adding a JS script as long as it doesn't include any sensitive information. JS is fully exposed to client, you shouldn't do it anyway.
But your situtaion it is better to create a site specific custom plugin and add JS using it.
Example :
function themeslug_enqueue_style() {
wp_enqueue_style( 'core', 'style.css', false );
}
function themeslug_enqueue_script() {
wp_enqueue_script( 'my-js', 'filename.js', false );
}
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_script' );
More Details : Plugin API/Action Reference/wp enqueue scripts | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "jquery, templates, javascript, page template, template include"
} |
Notice: Undefined index: host in /var/www/html/wp-includes/canonical.php on line 445
After changing siteurl ,home url form database it shows 3/4 errors called
> Notice: Undefined index: host in /var/www/html/wp-includes/canonical.php on line 445
>
> Notice: Undefined index: scheme in /var/www/html/wp-includes/canonical.php on line 465
>
> Notice: Undefined index: host in /var/www/html/wp-includes/canonical.php on line 444
>
> Notice: Undefined index: host in /var/www/html/wp-includes/canonical.php on line 444
I have no idea whats wrong with this. | When I change the url from the database I just put forgot to keep http before the ip address . When I set the http it works fine here. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 7,
"tags": "errors, rel canonical"
} |
Categories list loop - add separator every 3 categories
I have a code which shows categories list with images. Im using this plugin to attach image to category.
Code is:
<?php
$args=array(
'orderby' => 'name',
'order' => 'ASC',
)
?>
<?php foreach (get_categories( $args ) as $cat) : ?>
<h3><a href="<?php echo get_category_link($cat->term_id); ?>"><?php echo $cat->cat_name; ?></a></h3>
<a href="<?php echo get_category_link($cat->term_id); ?>"><img src="<?php echo z_taxonomy_image_url($cat->term_id); ?>" /></a>
<?php endforeach; ?>
My question is how can I modify this loop to add something (separator or text or something) every 3 categories. So theres 3 categories then separator then 3 categories etc. | <?php
$args=array(
'orderby' => 'name',
'order' => 'ASC',
)
$count=1; // A $count variable
?>
<?php foreach (get_categories( $args ) as $cat) :
if($count%3==0) // This condition will be true for 3,6,9,12..........
{
//Your Code ---
}
$count++ // Increment $count variable
?>
<h3><a href="<?php echo get_category_link($cat->term_id); ?>"><?php echo $cat->cat_name; ?></a></h3>
<a href="<?php echo get_category_link($cat->term_id); ?>"><img src="<?php echo z_taxonomy_image_url($cat->term_id); ?>" /></a>
<?php endforeach; ?>
I have added comments to understand. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "categories, loop, list"
} |
How to add an element right after the article using jQuery?
I am working on a wordpress plugin written in jQuery. I want to add a `div` element right after the article ends. Right now, I am doing this in the following way:
$('div.entry-content').append('<div class="my-div"></div>');
Will this be universal for all wordpress blogs? Is there a better way to do this? Thanks! | I think this is fine. But better do it like-
jQuery('div.entry-content').append('<div class="my-div"></div>');
Cause the `$` sign doesn't work some time with WordPress. Better if you wrap your `jQuery` code with this below code-
(function( $ ) {
'use strict';
// Write your jQuery code here.
// And here you can use $ or jQuery as your wish.
})( jQuery );
Now about `jQuery` method, you can also use `after()` or `insertAfter()` to add something after the article tag. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, plugin development, jquery"
} |
How do I make sure that my plugin only runs on article detail pages?
Basically, I want my jQuery plugin to run only on article pages, that is, not on the home page, or other pages. Right now, I am doing this in the following way:
if ( is_single() ) {
launchPlugin();
}
In other words, if the `is_single()` function returns true, I start my plugin. Am I doing it right? Is it universally acceptable for all WordPress blogs? | Yes, this should be correct. Is_single returns true on single post pages, both normal and custom post types. Note that if you also want to run your script on pages, you will need `is_singular`. The latter allows you to specify which post types the script should be included with, so it gives you more flexibility.
And yes, this should work for all WordPress blogs, though you should always wonder what happens if some other plugin interferes with yours. There's no 100% guarantee that it will always work. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, jquery"
} |
How to prevent authors from editing their post count?
The number of views is something I am very concerned about as it helps me understand how many people actually read the posts. I have bloggers working with me who may fake their article's popularity just by editing the "number of views" in the edit section of each article. How can I stop them from doing that?
I have added `User Role Editor` plugin for the same but I can't figure how to prevent author from changing post count.
Is there any other manner in which I can check the actual number and prevent the author from seeing/editing the same?
They are able to edit here:
. I get the email but it contains no url to click. Plugins are disabled. What shoud I do? | The problem is the `<` and `>` which surround the reset URL in `wp-login.php`. You can remove them using retrieve_password_message in your theme `functions.php` file like below:
add_filter("retrieve_password_message", "mapp_custom_password_reset", 99, 4);
function mapp_custom_password_reset($message, $key, $user_login, $user_data ) {
$message = "Someone has requested a password reset for the following account:
" . sprintf(__('%s'), $user_data->user_email) . "
If this was a mistake, just ignore this email and nothing will happen.
To reset your password, visit the following address:
" . network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login') . "\r\n";
return $message;
} | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 9,
"tags": "email, password, reset"
} |
Page permalink redirects to home page
I've recently switched to Linux Fedora, and I moved all my xampp files to my new installation, as well as importing the databases.
Now I'm facing an odd problem, a couple of weeks ago I've created a new page on Windows and called it Resources, and created the `page-resources.php` file for it, it was working well.
I'm trying to access the url `localhost/site/resources` which was the permalink for the page I created, however, it's redirecting me to `localhost/site/` which is the home page, I tried changing the permalink settings, turning off all plugins, resetting my `.htaccess` file, even changing my site url, but no chance, and I don't know what to do.
Note: if I change the page permalink and the page slug from files, it actually works !, like if I added a letter to the name to be `localhost/site/resourcess` as well as changing the php page slug file, it's loading the page.
**UPDATE: Fixed by clearing browser's cache data and cookies :3 :D** | **UPDATE** : I fixed it by clearing my browser's cache, it was caching files so it used the old copy.
**BONUS** : You can load a web page without loading your caches by using `Ctrl + F5` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, htaccess, linux"
} |
Change site title color on individual pages
Hi I've asked this question in the main stackoverlow section and have got several answers which sadly have not solved my issue (unless I am doing something wrong). So in a last ditch attempt hopefully i will get a more specific response by posting here in a more tailored section.....blabbering on.
Site : <
Is it possible to change color of the main title of the site without changing the color of other pages/posts on the site ? (if that makes sense).
I would like the 'Otis landscape design landscape architect & designer to be in white font and all other pages/posts/categories to remain in black font.
Just a heads up I am looking for a CSS solution as i am not clued up in php :O
Many thanks in advanced. | Ack i missed it.
Just add this css
//changes site title and slogan
.home .gk-logo-text.inverse > span {
color: white!important;
}
//changes site slogan only
.home .gk-logo-text.inverse > span + span {
color: white!important;
}
thanks @cjbj | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, css"
} |
How to put title slug into content when create a new post?
After finish type the title post from the title field, i want to put the slug automatically inside the content .. can i do this ?
ex Title : This is just an example
Permalink : example.com/this-is-just-an-example
Content : this-is-just-an-example | You have to use `the_content` filter.
Following example is to just adds a featured image set from the single post Edit screen which displays before the content on single posts only.
You can change it to display title and permalink.
add_filter( 'the_content', 'featured_image_before_content' );
function featured_image_before_content( $content ) {
if ( is_singular('post') && has_post_thumbnail()) {
$thumbnail = get_the_post_thumbnail();
$content = $thumbnail . $content;
}
return $content;
}
Source : Plugin API/Filter Reference/the content | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "slug, title"
} |
What is /wp-json?
I know about the REST API and I know what JSON is. My understanding is that to properly use the REST API right now it requires that the official plugin be installed. However when I hit the above directory even on sites that do not have the plugin installed I get data back.
What is generating this? Is this relatively new or has this been in place for a while? | That's the root URL for the REST API. All WordPress installs have it, but in 4.6 very few endpoints exist, mostly oembed and plugins. The core infrastructure for the REST API has been available since 4.5, with functions such as `register_rest_route` being available.
`/wp-json` itself is generating discovery data, listing the various available endpoints. You may notice a large number of endpoints if you have for example Jetpack
It's the content endpoints that require the WP API plugin, these are slated to be merged in with the 4.7 release | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 7,
"tags": "json"
} |
Why does WordPress have private functions?
Note: I am talking about `_wp_get_current_user();` not `wp_get_current_user()`.
If you check the function `_wp_get_current_user();` you can see the following statement:
> This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness. Use wp_get_current_user() instead.
Why does WordPress have these types of private functions? Why doesn't WordPress allow to use these types of functions for WordPress plugin or theme developers? | It is quite normal practice for code to not be a part of public API.
But much of WP code is ancient and procedural. There are no _technical_ ways to make a private function.
These are _semantically_ private, that is WP doesn't _want_ you to use them, but it cannot actually forbid you to. There is a long history of "private" WP APIs being actively used in practice by extensions.
The reasons for declaring something private vary from case to case. In this specific case you raised the reason seems to be that "public" version is pluggable, so moving implementation to a "private" version allows original to be replaced more easily / with less issues. | stackexchange-wordpress | {
"answer_score": 18,
"question_score": 7,
"tags": "functions"
} |
excerpt button not going to custom post page
Hi I made a custom post type using the CPT UI plugin, and have a excerpt button to go to it's full page. But when I click on the button, it just loads the front page (where the button is). Is there something wrong with the excerpt code? I'm currently using Understrap framework. Code below:
if ( ! function_exists ( 'all_excerpts_get_more_link' ) ) {
function all_excerpts_get_more_link($post_excerpt) {
return $post_excerpt . ' <p><a class="btn btn-secondary understrap-read-more-link" href="'. get_permalink( get_the_ID() ) . '">' . __('VIEW CASE', 'understrap') . '</a></p>';
}
}
add_filter('wp_trim_excerpt', 'all_excerpts_get_more_link'); | You to set the global $post, otherwise your `get_the_ID()` function won't work because this code is not in a Wordpress loop.
function all_excerpts_get_more_link($post_excerpt) {
global $post;
return $post_excerpt . ' <p><a class="btn btn-secondary understrap-read-more-link" href="'. get_the_permalink( get_the_ID() ) . '">' . __('VIEW CASE', 'understrap') . '</a></p>';
}
add_filter('wp_trim_excerpt', 'all_excerpts_get_more_link'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "excerpt, buttons"
} |
Getting posts via WP Query
Here is the scenario,
There are total 100 posts. In starting on the page, I am displaying 50 posts ( i.e. 1 to 50 ) on the page. There is one Load More button.
On the click of that Load More button, next 10 posts ( i.e. from 51 to 60 ) should be displayed.
Another click on Load More button, next 10 posts ( i.e. from 61 to 70 ) should be displayed.
Is there any way to get next few posts via WP Query? | Skip first 50posts
'offset' => 50
Pagination
'paged' => 2,
'posts_per_page' => 50 | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "wp query"
} |
Theme Check warning wrong direcory for theme
I am checking my theme with theme check and it is raising following warning:
> WARNING: Your theme appears to be in the wrong directory for the theme name. The directory name must match the slug of the theme. This theme's correct slug and text-domain is prisma. (If this is a child theme, you can ignore this error.)
Although page slug I have used is prisma and also tried to rename the WordPress installation directory to prisma but still the error is persisting. Can anybody guide me how to resolve the issue?
Thanks! | The problem is with your theme directory name. it usually resides here:
/wp-content/themes/
then check if your theme name and directory name matches. you can change it in your computer or FTP client easily. if through terminal, use this command:
$ sudo mv -v OLDDIRECTORY NEWDIRECTORY | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "themes"
} |
Show message from backend
I need to show messages on wordpress page editor, when a page is updated. I know there is a `admin_notice` hook to show messages. I have a `save_post_page` perfectly working on my code, but I need to know how to connect both of them and I don't know why?
Any help would be appreciate,
Best regards,
Ismael | The problem is that when a post is saved, there's a redirect back to the edit post page and the admin_notices action never runs. This means that any admin notice you put on any of the save post actions (save_post, transition_post_status, etc.) will be thrown away (since they're not persistent) during that redirect.
The workaround is to save a state (user settings/user meta, post meta, transients, options) which would signal that an admin notice should be shown, and look for that state on the next request.
add_action( 'save_post', function( $post ) {
// some checks here
update_user_option( get_current_user_id(), '_my_show_notice', true );
});
add_action( 'admin_notices', function() {
if ( get_user_option( '_my_show_notice' ) ) {
delete_user_option( get_current_user_id(), '_my_show_notice' );
echo '<div class="notice notice-success"><p>Some notice</p></div>';
}
});
Hope that helps! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, customization, notices"
} |
How to echo the translated custom field?
I have this function to echo the 'my_custom_field' value, and it works fine:
add_action('woocommerce_before_add_to_cart_form' , 'my_function');
function my_function(){
echo get_post_meta( get_the_ID(), 'my_custom_field', true );
}
But this only prints the value. I need to also print the translated title of this custom field. How can get this? | can you do this:
get_post_meta(get_the_ID(), '', true);
print_r($meta);
or
get_post_meta(get_the_ID(), 'my_custom_field');
print_r($meta);
the first will pull all custom post type on the current post, and the second restricts to the field. You should get an array and then you'll know which item in your array is the field title you're looking to pull. then you can use that to return title | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, custom field, hooks"
} |
How can I get WP to use templates in lower-level subfolder?
I want to add sub-directories to the 'page-templates' directory and thus be able to better-group associated files.
As WP won't normally read that deep, how can I do this? | Whilst you're correct in saying WP will only scan directories 1 level deep for templates, since 4.4 you have complete control over the `theme_page_templates` filter (you can now add to as well as remove from the list):
add_filter( 'theme_page_templates', function( $templates ) {
$templates['page-templates/another/directory/template.php'] = 'Another Directory Template';
return $templates;
}); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "templates"
} |
How do I use Wordpress PHP functions in my Javascript code?
Let's say I want to run the javascript function `launchMyPlugin()` only on post detail pages. At first, I was doing something like this:
**myPlugin.js**
if ( is_single() ) {
launchMyPlugin();
}
However, this obviously does not work since `is_single()` is a php function. What is the right way to do this then? Do I need to add the condition to my .php file instead? Thanks! | You can check is_single before enqueue the js file
add_action('wp_enqueue_scripts', '_enqueue');
function _enqueue(){
if(is_single(){
wp_enqueue_script(......);
}
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "plugins, plugin development, jquery, javascript"
} |
Check if Favicon is set in Customizer
There's this "Site Icon" option in the customizer, which allows you to set a favicon. I'm creating a theme which already has its own favicon.
How can I check if the favicon is already set in the customizer? | WordPress saves the Favicon as `site_icon` in the options table holding the attachment post ID. What you could do is something like this:
if( false === get_option( 'site_icon', false ) ) {
// Show favicon
}
Where `get_option()` will hit the default ( we provide as the 2nd parameter ) `false` IF the `site_icon` does not exist or one has not been uploaded through the customizer. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, theme customizer, favicon"
} |
How to use wp_get_recent_posts with many post types?
I've tried displaying many post types (separated by comma) and it didn't work. Is there a way to achieve this?
$args = array( 'numberposts' => '5', 'post_type' => 'cpt1, cpt2, cptn');
$recent_posts = wp_get_recent_posts( $args );
Thanks for your input. | Use post types as an array.
$args = array(
'numberposts' => '5',
'post_type' => array('cpt1', 'cpt2', 'cptn')
);
$recent_posts = wp_get_recent_posts( $args ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "functions"
} |
Setting Up PHP Workflow in Wordpress
I started a wordpress site about games, and I'd like to setup a workflow to allow php devs to work on the backend without fear of breaking something on the main site. How can I modify plugins so they don't affect the main site?
I can run a server locally, and make my modifications with that, but this would mean that everyone working on the site would have to setup their own local servers, which could create quite a bit of overhead.
So, again, my question is: how can I modify plugins so they don't affect the main site? | Having a local environment that is the same for all devs is pretty easy to setup using vccw.cc or basic-wordpress-vagrant.
Use Git for plugins and themes -- each as their own repo. Free private repos are available on Bitbucket.
Pass your DB around using WP-CLI or wordmove to sync settings and content. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, php, workflow"
} |
How to schedule and publish a post after it's ready?
I have a website which the post's contents are dynamically generated AFTER a post is published.
I'm using this code to generate the content i want:
`add_action( 'publish_post', 'generate_content'); function generate_content($post){ //some code here }`
This process can sometimes take up to 5 minutes, while the post is instantly published (I already set the php timeout to 600 seconds).
I want to schedule the post for when the function has finished it's task, or to save the post as draft and automatically publish it when it's ready.
Is there a way to achieve this? Any help is appreciated. | There might be two ways:
add_action( 'draft_post', 'wpse_246730_my_function' );
function wpse_246730_my_function( $post_id, $post )
{
// Do your things
// Just to stay safe
remove_action( 'draft_post', 'wpse_246730_my_function' );
wp_publish_post( $post_id );
add_action( 'draft_post', 'wpse_246730_my_function' );
}
Or make the post future status, and set a time after 10 or 20 mins to publish. Then use the following code:
add_action( 'future_post', 'wpse_246730_my_function' );
function wpse_246730_my_function( $post_id, $post )
{
// Do your things
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp cron"
} |
How can I include shortcodes within PHP?
I have a WordPress site using the following criteria from a plugin called MyCRED to determine whether to display content to the user, however that include consists of shortcodes and other non-PHP content. Is there a way to tell PHP 'treat this as if it is not PHP'? Shortcodes are key.
$minimum = 100;
if ( is_user_logged_in() && ( function_exists( 'mycred_get_users_cred' ) && mycred_get_users_cred( get_current_user_id() ) >= $minimum ) ) {
} | In your case do_shortcode should do the trick.
If your shortcode is just like `[my_shortcode]` then try `echo do_shortcode( '[my_shortcode]' );`
If you have opening and closing then `echo do_shortcode( '[my_shortcode]Inner text[/my_shortcode]' );` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, shortcode"
} |
Delete a category
I just recently deleted a category from my main menu and while the category itself has been removed, on my home page, the category title is still there.
It is for the web page: _IrishFilmCritic.com_.
We do a lot of different reviews and while we really didn't cover music reviews a lot, we gave it a shot.
After a while, I decided we weren't going to even bother with Music Reviews but if you go to the home page and scroll down, you will see _Music Reviews_ nestled in between _TV Reviews_ & _Book Reviews_.
How can I delete not only successfully, but definitely the concerned to unwanted categories ? | I took a look at your homepage, and I see what you mean. It looks like a widget is being used to generate that output, so take a look under **Appearance > Widgets** , and see if there is a widget area for the homepage used to generate the Music Reviews entry. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "link category"
} |
An unexpected error occurred when add theme
I recently install wordpress using wamp on my localhost. I try to change the theme by click on add new. I just want to explore the themes but got this message:
> An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the support forums. | Probably an error caused by trying to install it from the zip file. If it's in localhost try to unzip it and move the folder yourself to:
yoursite/wp-content/themes/NEWTHEME
And then try to switch to it from the wp-admin dashboard. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes"
} |
How to add Shortcode (font awesome) in widget title?
I want to show font awesome icon (installed) on the left side of the WordPress widget title. I found this shortcode that should do the work.
add_filter( 'widget_title', 'do_shortcode' );
add_shortcode( 'icon', 'shortcode_fa' );
function shortcode_fa($attr, $content ) {
return '<i class="fa fa-'. $content . '"></i>';
}
After adding this in `functions.php`, I should be able to add a gear icon in the widget title with below code from **Appearence>Widget**
[icon]cog[icon]
But it is not working. | I checked your code in my install. It works, except that you made a typo (missing backslash):
[icon]cog[/icon]
Few notes:
* You must make sure to **enqueue** the _Font Awsesome_ stylesheet.
* You must **close the shortcode** , like: `[icon]cog[/icon]`
* Remember to **escape** the class name with `esc_attr()`.
* Another shortcode idea: `[fa icon="cog"]` | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "php, filters, shortcode, widgets"
} |
error plugins learnpress in wordpress
Error when running plugins learnpress in wordpress
> Warning: include(/home/user/public_html/domain/wp-content/plugins/learnpress/templates/single-course/enroll-button-new.php): failed to open stream: No such file or directory in /home/user/public_html/domain/wp-content/plugins/learnpress/inc/lp-template-functions.php on line 1227
Warning: include(/home/user/public_html/domain/wp-content/plugins/learnpress/templates/single-course/enroll-button-new.php): failed to open stream: No such file or directory in /home/user/public_html/domain/wp-content/plugins/learnpress/inc/lp-template-functions.php on line 1227
Inside the File lp-template-functions.php on line 1227
do_action( 'learn_press_before_template_part', $template_name, $template_path, $located, $args );
include( $located );
do_action( 'learn_press_after_template_part', $template_name, $template_path, $located, $args );
view all file < | It looks like the file is missing but its has been called from one of the files.
After further review of the plugin files I saw that inside the LearnPress->inc directory in lp-core-functions.php file at 2291 line it adding the filter to add that missing file however that file is not inside the template files. Developer of the plugin has moved all the buttons file inside buttons.php in template folder without updating that filter.
So the solution is to remove that filter manually until the developer fix the issue or you can manually go the lp-core-functions.php file and comment out line 2291 like below
`// add_filter( 'learn_press_get_template', '_learn_press_enroll_button', 1000, 5 );`
Or you can add this line to removed that filter in somewhere in your theme functions.php
`remove_filter( 'learn_press_get_template', '_learn_press_enroll_button');` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
Run The Loop over array of post objects
Given an array of Post objects, how might one initialize The Loop so that the common Loop functions could be used:
$posts = array( /* WP_Post, WP_Post, ... */);
while ( have_posts() ) {
the_post();
the_title();
}
I am aware that I could simply loop over the array elements and pass to each function the ID of each element, however for reasons beyond my control using the actual Wordpress Loop is preferred here.
The array is provided from a function that I cannot alter. For purposes of discussion it might as well have come from unserialize(). | I'm using this in one of my custom widgets:
global $post;
$posts = array( /* WP_Post, WP_Post, ... */);
while (list($i, $post) = each($posts)) :
setup_postdata($post);
// use the template tags below here
if(has_post_thumbnail()):
?><div class="featured_image_wrap"><?php
the_post_thumbnail();
?></div><?php
endif;
the_title();
endwhile;
// don't forget to restore the main queried object after the loop!
wp_reset_postdata(); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "loop"
} |
adding google analytics via echo or between <php> tags
I'm adding the google analytics script in `functions.php`, and I was wondereing if there any concerns about adding it with a function like:
function add_google_analytics() { ?>
<script> GOOGLE ANALYTICS CODE </script>
<?php }
vs a function like
function add_google_analytics() {
echo "<script>GOOGLE ANALYTICS CODE</script>";
} | As long as you're quotes are escaped to render the final code correctly, you should be fine either way. That just a matter of preference.
If you go with the first route, you'll be able to migrate your scripts to an external source with very little extra effort. The second way can get a little annoying if you need to unslash quotes. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, google analytics"
} |
How to make search and replace in content through php
I actually can show content and change content while displaying post. Problem is that I am using RSS importer and after importing I want to make search and replace and correct data imported because I know what is wrong with it.
<?php
add_action('pmxi_saved_post', 'post_saved', 10, 1);
$my_post = array(
"ID" => $id,
"post_content" => "1",
);
wp_update_post( $my_post );
?>
this is code I am using. Problem is that "post_content" does not change to value 1. Basically this code should change whatever is in post $id to value "1".
Why is this not working? I cannot figure it out for 2 hours now. All examples I have are based on change content while displaying but that does not change content IN database, only what is shown. | From the documentation of WP All Import, the `pmxi_saved_post` action takes one parameter, `$id`, which is "the ID of the post/page/Custom Post Type that was just created."
So, your `post_saved()` callback should look like this:
add_action('pmxi_saved_post', 'wpse246838_post_saved', 10, 1);
function wpse246838_post_saved( $id ) {
$my_post = array(
"ID" => $id,
"post_content" => "1",
);
wp_update_post( $my_post );
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "content, the content, post content"
} |
Create Archive Page with Visual Composer
I have a custom post type and have the file created called archive-services.php in my theme. I want this archive page to be represented by a user created page in wp admin. This way the user can create the archive page and modify it. I have the page created in VC too. My issue is that I do not know how to connect them.
Right now I have the domain of the visual composer created page set up as "services" however when I go to the page the content is not loaded even though I have a standard loop setup on the archive-services.php file.
Any ideas? | By default, WordPress does not offer a way of editing `archive`s. (archive templates are utterly useless in any real life applications, if any cares about my opinion).
You would have to create a theme option/settings page, where you would control the styling of an `archive` template.
But, quicker would be to just not use an `archive` template at all and instead put a `shortcode` into a normal `page`, where you could then use Visual Composer (you can even make your shortcode a VC element). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post type archives, visual editor"
} |
Update media library files after upload via FTP
I had to upload many files massive and directly to /wp-content/uploads/[year]/[month]/ but those files does not appears in Dashboard>Media>Library
Is there a way to update or refresh it to load those files or it's simply happening because it should have been writen also in database and I avoided it? In this case, is there a plugin to fix it? | Avoid direct upload WordPress doesn't scan upload directory for new files, instead use WordPress media uploader to add files WordPress automatically creates folder and store them accordingly.
But you can use this plugin to import those uploaded files into WordPress, it should help you < | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 15,
"tags": "media, ftp, library"
} |
Change the backend language of a single plugin
I'm managing a WordPress installation which main backend language is Italian, mostly due to the needs of the Authors and Editors.
I found a plugin that functionally fits my needs perfectly, but it gets installed with Italian localization by default, which translation of the backend is really poor at the moment to the point of being misleading in some functions.
Is there a way I can keep the admin backend in Italian but show that particular plugin in English?
Thanks in advance for your time. | Luckily the plugin developer made two separate file sets, one for frontend and one for backend. So I was able to delete the it-IT backend files, copy the en-US ones and rename the copies as it-IT.
So wordpress thinks it's loading the Italian backend translation while instead the English one gets loaded.
And being frontend and backend separated, nothing changed on the actual site.
Hope this helps someone! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, wp admin, translation, language"
} |
Accessing $post variable from template part
Here is a section of code that I have in a template file — to display sub-navigation if the page has child-pages:
<?php // display sub-nav if page has children ?>
<?php $children = get_pages(array('child_of' => $post->ID)); ?>
<?php if (count($children)) : ?>
<ul class="nav nav-tabs">
<?php foreach ($children as $val) : ?>
<li role="presentation">
<a href="<?php echo get_permalink($val->ID); ?>"><?php echo $val->post_title; ?></a>
</li>
<?php endforeach; ?>
</ul>
The code works fine when in the template file `page.php`, but if I put it all into a new file — `nav.php` and then include it with `<?php get_template_part( 'include', 'nav' ); ?>` then it stops working.
How can I set it so that the `$post` variable still works? Do I need to do something with global variables? | is your file name is 'include-nav.php' or it is placed inside 'include' folder ?
if not then simply call it by passing name of **nav.php**
<?php get_template_part( 'nav' ); ?>
you don't have to pass include keyword to call template.
Hope this help :) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "posts, templates, page template, variables, get template part"
} |
Woocommerce product name
For a purpose im passing woocommerce values to an array like this :
'name' => $_POST['billing_first_name'],
'phone' => $_POST['billing_phone'],
'email' => $_POST['billing_email'],
'note' => $_POST['order_comments'],
Now I'm stuck finding one of the values. The name of the ordered product.
;
$items = $order->get_items();
Then you can loop through results to add the product name to your array.
foreach($items as $item){
$product_names .= $item['name'] .' ';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
Present NextGen Gallery album through link
I'm using the NextGen Gallery and would simply like to present one of my albums in a popover gallery through an anchor link.
Currently I'm only aware of being able to use the `ngg` short code to insert an album into my page. This is not what I want. I don't want the images to show on the page. I would like to have a link and upon clicking the link, my NextGen album is presented in a popover gallery.
I don't care which popover gallery is used. Lightbox, Fancybox, etc. any will do.
Is there a short code I can use with `ngg` or maybe an additional plugin? | With NextGEN Pro you use the Pro Lightbox. Then insert an album with it set to open galleries in the Pro Lightbox. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin nextgen gallery"
} |
Does using `add_action( 'init'...` cause performance issues?
Am I using `add_action('init'` correctly?
I want to display some data if a user visits `example.com/?my_plugin`
At the moment I'm using...
<?php
add_action( 'init', 'my_plugin' );
function my_plugin()
{
if( isset( $_GET['my_plugin'] ) ) {
...
echo $data;
}
}
This will run every time any page on the blog is loaded, as I understand it. Does that present a performance issue?
Is there a better way I could accomplish this? | Performance impact of hooked functionality is determined by how often hook fires and how intensive the operation is.
`init` only ever fires one per load, so multiple runs are not a factor for it.
Mostly the thing you need to pay attention to is context. If your logic fires on every load and result is conditional the first thing it should do is determine if the context is the one you want. In all other cases that it the _only_ thing it should do.
As long as your context check is lightweight the performance impact should be perfectly insignificant.
If your context check _is_ heavy for some reason you might want to find a more specific hook (such as those in template loader logic) that would fire less and in more narrow circumstances. But for something as simple as example you made that won't be necessary. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, plugin development, actions"
} |
100% width Featured Image Size
I have looked all over the place for an answer and I cannot seem to find anything of relevance so I thought maybe someone here could provide some insight.
I want to use the featured image of a post or page as the background for the title area of the post/page similar to this <
I know how to get it done, thats not the problem. My problem is I want to add a 100% width and (pixelsize) height usng `add_image_size();` image size in functions.php.
Anyway of doing this? ANy help is greatly appreciated and thank you in advance.
*yes I looked at all of the "Questions that may already have your answer" that popped up and none of them had an appropriate answer...lol or | Ack, nevermind I just discovered that using `get_the_post_thumbnail( $post_id, 'full' ); // Original resolution`
will use the width and height of the featured image.
I do apologize for wasting everyone's time. I should have been a little more patient ;) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "themes, post thumbnails"
} |
Unable to Edit Destination settings - 1and1 hosting
I am trying to host my wordpress site on 1and1 server. But I all the help documents point to editing destination under domain settings in my control panel.
Unfortunately, I am unable to see that option
 {
$post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID'] ;
if( !isset( $post_id ) ) return;
$template_file = get_post_meta($post_id, '_wp_page_template', true);
if ( $template_file == 'page-custom-one.php', 'page-custom-two.php' ) {
remove_post_type_support( 'page', 'editor' );
}
} add_action( 'admin_init', 'wpcs_disable_content_editor' ); | Your if condition is wrong and generates a syntax error. You need an logical operator to check for multiple conditions. Therefore your code should look like the following:
if ( $template_file === 'page-custom-one.php' || $template_file === 'page-custom-two.php' ) {
remove_post_type_support( 'page', 'editor' );
}
You could also check for multiple values with the in_array function like this:
if ( in_array($template_file, ['page-custom-one.php', 'page-custom-two.php'], TRUE) ) {
remove_post_type_support( 'page', 'editor' );
}
Besides, you should always use strict comparison over loose comparison to prevent unexpected behaviour. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, visual editor"
} |
How to increase script execution time at my server
I am trying to run string locator plugin to find some strings in my theme directory. but whenever i try to run this plugin, following error ocures "Warning The maximum time your server allows a script to run is too low for the plugin to run as intended, at startup 2 seconds have passed"
I have tried to increase max exeecution time for script in php.ini by going to Xampp control panel click config> php.ini .... but nothing changed. is there any other way to make this plugin work? thanks! | The author of the plugin says it this problem was fixed in release 2.0.3 . You may also check the original thread in WordPress support . | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, theme development"
} |
Using esc_url() on a url more than once
If I have a front-end post form where a user enters a url, is it OK and recommended to use `esc_url()` twice - once for cleaning the input before using `update_post_meta` for database storage, and again on output.
// escape url before using update_post_meta
update_post_meta( $post_id, 'url', esc_url( $url ) );
// escape url on output
echo esc_url( get_post_meta( $post_id, 'url', true ) );
Any help appreciated. | It's okay to use it more than once, but not encouraged. However, in your first example, you're saving the URL to the database. When you do that, or when using the URL in the `wp_remote_*` context, or a redirect, or any other non-display context, you should be using `esc_url_raw()` instead.
Also note that `get_post_meta` will return an array, unless the third argument `$single` is set to true. If you're dealing with a single key-value pair you'll want:
echo esc_url( get_post_meta( $post_id, 'url', true ) );
Hope that helps! | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "escaping"
} |
How do I fix the "sorry, you are not allowed to access this page" error I get on the "plugins > settings" links?
I just upgraded to WordPress 4.6, and now when I try to click on the **Settings** link on some of my plugins I get this " **Sorry, you are not allowed to access this page.** " message.
I can active/deactivate the plugin fine but for some reason I can't go under the settings view.
I tried following some of the methods that other people used to fix this; like adding a new administrator and updating the " **wp_capabilities** " and " **wp_user_level** " values in the DB but it still does not work.
Does anyone know how I can further debug or resolve this issue? | I discover this message “Sorry, you are not allowed to access this page” mostly occur when various WordPress sites are in the same phpMyAdmin – all bearing the same table prefix, irrespective of the database name. I can’t tell how many WordPress sites are expected to be in the same phpMyAdmin with the same table prefix. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 4,
"tags": "plugins, errors"
} |
querying posts with a custom status
I am trying to query some wordpress posts, they have a custom post status of `closed`.
When I run this query, they get returned despite their custom status being set to `closed`, even though I've asked for `published`:
$now = strtotime(date('d.m.Y H:i:s'));
$args = array(
'post_type' => 'vacancy',
'post_status' => 'published',
'posts_per_page' => 1000,
'orderby' => 'meta_value_num',
'meta_key' => 'wpcf-closing-date',
'meta_query' => array(
array(
'key' => 'wpcf-closing-date',
'value' => $now,
'compare' => '<=',
)
),
);
$vacancies = new WP_Query($args);
I would have expected that only posts with the `post_status` of `published` would have come back. Anybody any ideas why this is returning `closed` posts? | The correct `post_status` for a 'published' post is 'publish':
'post_status' => 'publish', | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp query"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.