INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
503 Login WordPress
Anyone have experience failed to login and got the 503 Service Unvailable?
My WP site hosted on GoDaddy Managed Hosting. They said cause of this is came from the WooCommerce. I tried to disable this but the error still occured.
Thanks | I've had 503 errors when using shared hosting services with Fasthosts / Rackspace etc. Typically, they don't last long, but if yours are - then there is something going on with the server you are sharing. You might want to check that the memory limit in the config is 96 MB but that shouldn't be causing the issue. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "login"
} |
Override css rules of a plugin within my own theme
I want to override some rules of a plugin css file within my own theme so next time that I updated that plugin, my settings of that plugin be in a safe place . currently I copied that css file into my theme and changed some rules.So then I need to override this rules. I think found an answer that is related to my question (HERE) but I can't understand this code. how it works?
add_filter( 'style_loader_src', 'wpse106104_replace_stylesheet', 10, 2 );
function wpse106104_replace_stylesheet( $stylesheet_src, $handle ){
if( 'plugin-script-handle' == $handle ){
$stylesheet_src = get_template_directory_uri() . '/css/themes-copy-of-plugin.css';
}
return $stylesheet_src;
} | The `style_loader_src` filter is used to modify/filter the src (url) of a stylesheet. The function callback accepts two parameters, the first is the original src and the second the handler of the stylesheet. The handler is the first parameter of `wp_enqueue_style()` used to enqueue the stylesheet.
So, to replace a stylsheet source with another one you should check the handler to know wchich stylesheet it must replaced, in the code you posted the checked handler is `plugin-script-handle`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, themes"
} |
Adding a menu item for a Custom Post Archive
I've created a Custom Post type (`project`) and it works perfectly. I have a custom archive page (`archive-project.php`), and that works great, too, but what's the best way to add a link to that custom post archive in the site's primary menu?
I've created a Custom Link (see below), but is there a better way that isn't so hard coded?
.
When you are sure that archives are enabled and your CPT is still not visible you can reveal it through the Screen Options menu at the top of the screen (thanks, Nathan Hornby).
 by a sql command `create database wordpress;`, that is it.
The wordpress seems to work, because I can run and see that with `locallost` under a browser.
Then, I tried to install another wordpress projet (which works) that my colleague had already customised. He sent me all the wordpress files and a database file `asyc.sql`. I created another projet under eclipse and imported the database by the following command line:
`/opt/lampp/bin/mysql -u wpuser -p wpuser asyc < asyc.sql`
And here is the result:
. Is there any way to do that? at least reach to minumim file load... . | I'm not really sure why you'd want to do this...but the only thing I can think of that might work is something like this:
function prefix_block_resources(){
if(is_admin())return; //I can't imagine any scenario where blocking scripts in the admin area would be wise.
global $wp_scripts;
global $wp_styles;
$wp_scripts->queue = array();
$wp_styles->queue = array();
return;
}
add_action('wp_head', 'prefix_block_resources');
That will block any styles and scripts that have been loaded using the WordPress API, it won't do anything about styles/scripts that have been hardcoded into the theme. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, css, javascript"
} |
How can I see my theme's text domain?
Where can I discover my current theme's text domain for use with translation (GetText)? | Your theme's text domain is defined in your Theme Header in `style.css`. For example:
/*
* Plugin Name: My Plugin
* Author: Otto
* Text Domain: my-plugin
*/
The text domain should match your theme's 'slug' (ie. the name of the folder where your theme is stored).
Read more: < | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "translation, textdomain, xgettext"
} |
What are the issues associated with upgrading MySQL for Wordpress?
What are the issues associated with upgrading MySQL from 5.1 up to 5.5 for a server hosting multiple Wordpress sites?
Will there be problems with the database after the upgrade?
I have Plesk 12 installed on a Ubuntu server and I can update to the latest version of MySQL (I believe only 5.5) but I don't know if this will cause issues? Is upgrading MySQL straightforward in terms of database compatibility (upgrading 5.1 to 5.5) or is it likely that things will break? | It depends on what version of WordPress your sites run. If you are up to date, you shouldn't have much of an issue. According to the official WordPress hosting guide, any version of MySQL version 5.0.15 or greater is supported for WordPress. You can give this article a read and see if there is anything that jumps out at you as being particularly dangerous.
If you are running a version of WordPress that is very old you are more likely to run into issues; however, if you are running a version that old you should strongly consider upgrading WordPress regardless.
That said, there can always be issues with this type of upgrade and if you decided to go forward with it you should make sure you have backups of everything. If WordPress compatibility is your only concern you should be ok. If this is for a production environment, I would strongly suggest testing both the upgrade and your sites on a dev server rather than doing a live in-place upgrade. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "mysql"
} |
Making sub-menus exclusive
I don't really know how to explain what I'm looking for so bare with me here. On my site I have a side menu with a bunch of sub categories with a few items in each. I want to know if there's a way to close all the other open subcategories when I open another one, for example:
1. Animals
----A. Cats
----B. Dogs
2. People
----A. Samantha
----B. Daniel
When I press on "Animals" I want "People" to close and vice versa so that the menu is always:
1. Animals
----A. Cats
----B. Dogs
2. People
or
1. Animals
2. People
----A. Samantha
----B. Daniel
and not open all at once. I hope you guys understand what I'm looking for. | I'm making some assumptions here, like you are the one writing the code for the theme, or at least have the ability to modify the JavaScript in some way.
You can accomplish this using jQuery using code along these lines:
$(document).ready(function () {
$('.parent ul').slideUp();
$('.parent > li > a').on('click', function (e) {
e.preventDefault();
var $this = $(this);
$this.parent().siblings().find('ul').slideUp();
$this.siblings('ul').slideDown();
});
}); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "menus"
} |
Make one page inaccessible to search engine spiders
To prevent spiders from accessing a page one can just add within tags. Is there a way in WordPress to achieve this, for one page in particular, through some plugin or even from the native dashboard? | Yoast SEO is set up to do this for you on a per-page basis. If you aren't using Yoast already, I'd strongly recommend it - there are advanced controls for SEO, indexing, redirecting, etc. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "search engines"
} |
get_posts array 'between' not behaving
if I make the query of
$apartments = get_posts( array ( 'post_type' => 'apartment','meta_key' => 'bedrooms','meta_value'=> array(4,12) , 'compare' => 'BETWEEN' , 'type' => 'NUMERIC'));
I only get 4 and 8 bedroom apartments.
if I make the query of
$apartments = get_posts( array ( 'post_type' => 'apartment','meta_key' => 'bedrooms','meta_value'=> array(4,5,6,7,8,9,10,11,12) , 'compare' => 'IN' , 'type' => 'NUMERIC'));
I also get 7 bedroom ones...
Why is the top item not seeing the 7 bedroom apartments? Am I not using BETWEEN properly?
Thanks | As you are looking at post IDs, you should be using meta_value_num instead of meta_value as your key. This will indicate to WP how to handle the comparison. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "get posts, meta value"
} |
How to allow users to write jetpack custom post types?
I am using latest version of WordPress and jetpack. I have used **custom post type ui** plugin for custom post type which allow user to write custom posts, but this is not supporting **jetpack publicize** feature.So i have to use jetpack post type for **publicize** support.But jetpack post types don't allow users to write. Can i give users capability to write jetpack post types ? | No need to use Jetpack Post Types feature for that. Just use the following code to enable Jetpack Plublicize for any custom post type of your theme/plugin. Place it in `functions.php`:
/**
* Enable Jetpack Publicize Support for CPT
* --------------------------------------------------------------------------
*/
function wpse20150812_jetpack_publicize_support() {
add_post_type_support( 'mycpt', 'publicize' );
}
add_action('init', 'wpse20150812_jetpack_publicize_support');
Replace the `mycpt` with your registered Custom Post Type.
**Reference:** jetpack.me - Support | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin jetpack"
} |
load language file
I want to load my French language file into my Arcade Basic theme. There is a language file, `arcade.pot`, and I translated it using PoEdit. I don't know how to add it, there is a function, in `functions.php`,
load_theme_textdomain( 'arcade', BAVOTASAN_THEME_TEMPLATE . '/library/languages' );
but i'm not sure how to use it, I try like this,
load_theme_textdomain( 'fr_CA', BAVOTASAN_THEME_TEMPLATE . '/library/languages' );
`fr_CA.mo` is my language file. | you don't need to edit functions.php (moreover don't edit this line or it will break the localisation of the theme, because `arcade`, is the code used to know where to search translations)
according to the line you read in functions.php, you have to put fr_CA.mo and fr_CA.po in `wp-content/themes/arcade-basic/library/languages` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes, localization, translation"
} |
Change CSS based on is_user_logged_in
How do I activate certain CSS lines depending on if a user is logged in or not?
**Here's how it looks:**  | You can use the `logged-in` class added by `body_class` to target your CSS rules.
.container { height: 160px }
body.logged-in .container { height: 30px } | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "php, css, users, login"
} |
User can manage one page accessible by everyone?
I'm creating a local site for my community. On this site we feature tutors in the area for hire. I'd like to have a section of the site where anyone can go and click on and see a list of tutors based on different criteria, like area or age group they teach. I'd like for the tutors to be able to login and edit their own page with their info or resume.
When someone views the tutor section, they will see a list of tutors, perhaps only preset snippets of info, they'll have to click on an action button to view the tutor's full profile page (the page that tutor created).
Is there some code to call user created content to a page? I'm looking for the answer to let a tutor make an account, sign in and edit their profile or page, and then I'll have to show snippets of that page on the front-end and link to the full page they made. | As you may or may not be aware WordPress provides a profile page in the admin for each registered user (including the admin of course!): `<
On that page you will see a number of fields that can be edited / customized including a `Biographical Info` field.
To fetch and output a field from this page for a particular user you can use the `get_user_meta` function like so:
$bio = get_user_meta( $user_id, $key );
`$key` could be the string `description` which corresponds to the `Biographical Info` field.
You may want to take a look at the `get_user_meta` Codex page (might be of special interest to output available data so you can correlate fields from the admin with valid `$key` values based on fields content). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "users, profiles"
} |
What is files.wordpress.com?
I observed some sites like Tech Crunch and their Image URL is showing up as techcrunch11.files.wordpress.com/xyz If there is a way to upload images to Wordpress server, then my websites server load will reduce. Do you have any idea what is it? I couldn't find it on Google. I get redirected to wordpress.com when I try to access files.wordpress.com | > CDN / front-end caching: all scripts and stylesheets are served from our CDN. Images are served from our dedicated *.files.wordpress.com domain.
<
That page should answer your question regarding the WordPress.com CDN. cybmeta correctly stated that it is for VIP WordPress members only. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wordpress.com hosting"
} |
Baskerville Theme - How to use the masonry grid layout on other pages
I am using the Baskerville theme which looks great but I haven't been able to replicate the Masonry layout on other pages. It works fine on the Home page but there is no template that facilitates this for other pages.
I have tried asking on the offical Baskerville support forum but no one seems to know how to accomplish this.
Here is a demo of how the Home page looks | The easiest way to do this is to make a Tags or Category page. The Masonry layout is called on these by default. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes, masonry"
} |
setting taxonomy term to bulk posts using ids
Is there any way to insert a taxonomy term to different posts whose ids are known in bulk. For example, suppose we have custom post types with ids 4522, 4524, 4526, 4528 and 4530; how can I insert a taxonomy term 'football' in taxonomy 'sports'. Thanks The code used in index.php
<?php
$post_ids = [57542, 57544, 57546, 57548, 57550, 57552, 57554, 57556, 57558, 57562, 57564, 57566, 57169, 57192, 57189]; // array of post ID's
foreach ( $post_ids as $id ) {
if ( !has_term( 'geography', 'objective-questions', $id ) ) // Check if term is not yet attached to post
wp_set_post_terms(
$id, // Post ID
'geography', // Term slug ( or can be term ID )
'objective-questions', // Taxonomy name
true // Only append the term, do not replace
);
}?> | I hope I understand this correctly. You can simply just add your post ID's in an array and then use a `foreach` loop to loop through the ID's and checking whether or not they have the term to assign or not, and if not, assign the term to the post
$post_ids = [4522, 4524, 4526, 4528, 4530]; // array of post ID's
foreach ( $post_ids as $id ) {
if ( !has_term( 'footbal', 'sports', $id ) ) // Check if term is not yet attached to post
wp_set_object_terms (
$id, // Post ID
'footbal', // Term slug ( or can be term ID )
'sports', // Taxonomy name
true, // Only append the term, do not replace
);
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "terms"
} |
Nonce for Trashing Item
I have a custom admin page.
On it, I have created a filtered list of the custom post type based on postmeta data.
I have to create a link to delete that post.
I am trying to figure out how to create the link with a nonce.
sprintf('<a href="post.php?post=%s&action=%s&_wpnonce=%s" class="link-course-delete">Trash</a>',$item['ID'],'trash',wp_create_nonce(???))
I am not sure what value to pass to wp_create_nonce to make it work. | I found the answer - this contains sample code which helped me resolve the issue.
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "nonce, trash"
} |
rewrite_rule - working fine but broken for pagination
I'm having an issue with me rewrite rule works fine here:
example.com/resources/
example.com/resources/articles/
but when i use pagination to the next page i get a 404 here:
example.com//resources/articles/page/2/
example.com//resources/articles/page/3/
example.com//resources/articles/page/4/
I was able to write two rewrite rules but now instead of getting a 404 page, the page refreshes with same content but URL changes here is my rewrite rules hopefully some one can help?
add_rewrite_rule( 'resources/([^/]+)/([^/]+)/?', 'index.php?taxonomy=res_category&term=$matches[1]&post_type=$matches[2]', 'top');
//added for page turn on pagination
add_rewrite_rule('resources/([^/]+)/([^/]+)/page/([0-9]{1,})/?', 'index.php?taxonomy=res_category&term=$matches[1]&post_type=$matches[2]&paged=$matches[3]', 'top');
thank you ahead for any help. | I figured it out! I had too many parameters trying to match and had to replace "[^/]+" with "(.+?)" i was able to get this with just one rewrite rule here is the final code:
add_rewrite_rule( 'resources/(.+?)(/page/([0-9]+))?/?$', 'index.php?taxonomy=res_category&term=$matches[1]&paged=$matches[3]', 'top');
now the problem i have now i get a 404 on the post itself if i click on an article ??? any clue why?? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, pagination, rewrite rules"
} |
Referring to site URL in shortcode argument
Apologies for the noob question -- have searched extensively, and it's probably a forehead-slapper.
A plugin I'm using offers a shortcode that takes a URL as an argument; I should set that argument to the URL of a particular page on my site. For example:
[cool-shortcode arg_needing_URL="URL of site page goes here"]
How can I avoid hardcoding the URL? I'm working on localhost for the moment, but I'd like the argument to work no matter where the code is hosted. I could tinker with the PHP for the shortcode to allow a special argument syntax meaning "look up this constant," but that feels like using a chainsaw to open an envelope. Does WP have a syntax for referring to constants from your content? | To answer the heart of your question: no, WordPress does not have a way of referencing posts by ID/slug/etc. within the post content. In fact, probably the recommended way to do that is with a...shortcode! Even that wouldn't help you in this case, though, since you can't nest shortcodes without a plugin.
So I'd recommend you use your own shortcode, or plug theirs if it's a pluggable function. Simply replacing their URL argument with a `get_permalink()` that accepts an ID from the shortcode is probably all that's required. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode, site url"
} |
Widget Admin - Form Submit Event?
I'm creating a widget, and cannot figure out how to get an event right before the person clicks "save" or presses the enter button on the widget admin panel. What would be the javascript code to get the event on the widget admins' form submit?
Example:  and do some work right then or figure out if you want to allow the `click` to "go through" or not based on some validation for example.
jQuery(function($) {
// We are binding to the body so that the code
// will work for future elements added to the DOM
$('body').on('click', '.widget-control-save', function(ev) {
var my_validation = true;
if ( my_validation ) {
console.log('widget save!');
} else {
ev.preventDefault();
ev.stopPropagation(); /* We are capturing the event so it won't bubble up. */
}
})
}); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "plugin development, widgets"
} |
Get list of taxonomies associated with users
I've seen Justin Tadlock's post on creating taxonomies for users, so I know that it's possible to do that.
But how do you get a list of all of the taxonomies associated with `users`? For posts and CPTs you can use `get_object_taxonomies( $post_type );`. What's the equivalent for users? | Strictly regarding your question: `get_object_taxonomies( 'user' );` since `user` is the `$object_type` that it is used when the author registers the taxonomy. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom taxonomy, query, taxonomy"
} |
How to allow customers to input a text as a product variation *and* charge per character?
I'm looking for a way in Woocommerce to add a product variation for customers that will allow them to put in their name/custom word(s) up to a certain character limit and the additional price will be calculated based on the number of characters in that input.
Ideally there will be a set price for a certain number of characters and then an additional fee for any characters beyond that (e.g. £x.xx for up to 5 characters, +£y.yy per character with a maximum of 10 characters).
Any code/plugin free/paid solutions welcomed.
Many thanks! | I have been working with a plugin called TM Extra Product Options and I am fairly sure you could achieve your goals using that. It isn't the prettiest plugin from a UI perspective, but it has a lot of functionality and good support if you use their forums.
You could use a select box for number of characters and then set a **conditional field** to appear when they make a choice in the characters select box.
Good luck! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, php, woocommerce offtopic"
} |
Custom search page and url in multilanguage
I just made a custom search page for my website in Wordpress. But I have an issue:
Case 1: mydomain.com/?s=test....Work
Case 2: mydomain.com/search/test....Work
Case 3: mydomain.com/en/?s=test....Work
Case 4: mydomain.com/en/search/test....Doesn't work and return 404 page.
I created a search page using my custom template. I changed the url to both languages to `/search` and `/en/search` respectively. But I cannot make the last case to work.
Here is the form in case you need it.
<form action="<?php echo site_url(); ?>" class="search-form" method="get">
<input type="text" name="s" placeholder="<?php _e('Search request here', 'wproto'); ?>" value="<?php echo get_query_var('s'); ?>" />
<button type="submit"><i class="fa fa-search"></i></button>
</form> | I managed to solve the problem myself. I had to flush the permalinks on the English admin page. Now all of the above urls work. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "search, multi language"
} |
Can you check if a post WYSIWYG field has an image in it?
I'm using Advanced Custom Fields and a WYSIWYG field type. Can you determine via php if that field has an image in the content OR is there a better was to evaluate this.
For example, if I upload an image into the editor and float if right of the text - I intend on treating the rendered container differently than a container without the image. | There isn't really a built-in way in WordPress to determine if a content field _has_ an image in it, but you can use standard PHP functions to check. For example, I've used a similar technique to check if a post's featured image has also been inserted into the post content, and if so, haven't shown the featured image again.
You haven't included any of your code, so this is just a sample you'll need to work in to what you already have.
The `strpos()` function will tell you if a specific string is inside another string. For example:
if( strpos( get_the_content(), '<img ' ) ){ /* this content has an image */ }
You could perhaps use this to add classes to your content container, so you can treat it differently in the CSS:
<?php
$image_class = strpos( get_the_content(), '<img ' ) ) ? 'has-image' : 'no-image';
?>
<div class="post-content <?php echo $image_class; ?>"> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "images, advanced custom fields, conditional tags, wysiwyg"
} |
Returning One custom taxonomy term name
I have a custom taxonomy called cities and right now the only city is las vegas. I am trying to use the code in question to echo "Las Vegas" - for the posts that are associated - on the search results page, taxonomy page and single post page.
Las vegas wouldnt be the only city, but each post should only be associated with 1 city therefore I just need the term associated with the post. As of now with the code Im using, the term is echoing for every post, even those not in the "City" category.
<?php $terms = get_terms( 'city-type' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
echo '<span>' . $term->name . '</span>';
}
}; ?>
Im using in the loop, what am I doing wrong? | You are fetching all the terms of your taxonomy, Use this instead :
$terms = wp_get_post_terms(get_the_ID(), 'city-type');
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
echo '<span>' . $term->name . '</span>';
}
}
**Note :** First argument to the function is id of the post, get_the_ID() will work fine on single post details page and within loops. Function reference on WordPress | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom taxonomy, loop, templates, terms"
} |
Tried to move blogs to a new server - "white screen of death"
I tried to migrate my old blogs to a new server. The domain remained the same (it was also transfered to the new server). To perform this task I tried to follow these steps: <
When I now visit the moved blogs, I get nothing more than the "infamous white screen of death".
The wordpress version seems to be 4.1.2 The moved blog should be found at < The old blog is at <
Can you help me to get this straight?
(X-post: < | You may not have configured Apache. Add this line in your `apache2.conf` file:
AddType application/x-httpd-php .php .htm .html
Evidently, you should make sure you actually have installed and activated the PHP module first and foremost (the above Apache directive might not even be necessary in this case). In this regard, you can visit the `/etc/apache2/mods-enabled/` folder and look for the `php5.load`, `php5.conf` files. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "migration, fatal error"
} |
Getting error Parse error: syntax error, unexpected 'add_filter' (T_STRING), expecting function (T_FUNCTION)
I am getting error
Parse error: syntax error, unexpected 'add_filter' (T_STRING), expecting function (T_FUNCTION)
when i write the below code in my plugin class file. but this is the only easiest method i saw to get the screen options working. is that code needs to be placed somewhere else?
function pippin_set_screen_option($status, $option, $value) {
if ( 'pippin_per_page' == $option ) return $value;
}
add_filter('set-screen-option', 'pippin_set_screen_option', 10, 3); | My guess would be you have just dropped filter into a class body in between the methods. That is invalid PHP and not going to work.
First you need to call it from where code makes sense, _inside_ another class method or from outside a class.
Second you cannot hook methods by their name alone, you need to use proper callback with a name of the class. Examples would be `[ __CLASS__, 'method_name' ]` (static method) or `[ $this, 'method_name' ]` (non-static method in class instance).
And finally if you are new to PHP then spending some time with PHP manual is **highly** recommended, it will save you a lot of time in dealing with WordPress. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, screen options, screen columns, screen layout"
} |
Is /wp-login.php?redirect_to[] exploitable?
I have a wordpress site, against which I ran a penetration testing tool (debug mode was on at the time)
It reported a (medium severity) issue in that errors were being displayed, and cited
> `/wp-login.php?redirect_to[]=blah`
>
> as triggering a warning: `urlencode()` expects parameter 1 to be string, array given in `/home3/.../wp-includes/general-template.php` on line 340
When I turned debug mode off, and replayed the session the redirect took place, and redirected me to /Array
Which concerns me that wordpress may be trying to evaluate the querystring parameter name in some way that is exploitable.
Am I being overly paranoid? | I think this is nothing to worry about.
The redirect target is sanitized and validated a lot. To be honest I think I haven't seen any part of the WordPress code where so many checks happen for the most obscure attack vectors.
Finally when you cast an array to a string `Array` is returned which is what you've seen.
> Arrays are always converted to the string "Array";
>
> Source
This happens in `_deep_replace`.
So my personal opinion is this should be fine. Let's see what other people say. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "security"
} |
How not to strip leading zero in advanced custom fields
I have custom field for phone number but the leading zero is not saved in db
I tried to format the field as number and text but the zero is not showing | Just make the field type as text and it will work | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "advanced custom fields"
} |
BuddyPress activity on edit post for a CPT
I have a Custom Post Type `classified` I figured out how to record an activity in the BuddyPress activity stream whenever a new post of type `classified` is created.
What I am specifically looking to do is either modify the above code or start fresh so that whenever a **post of type`classified` is edited** a new activity is recorded.
Here is the inspiration for the original code if it helps
< | Use the `save_post` hook. Try something like:
function jude_classified_activity_entry( $post_id, $post, $update ) {
$slug = 'classified';
if ( $slug != $post->post_type )
return;
bp_activity_add(
// etc
);
}
add_action( 'save_post', 'jude_classified_activity_entry', 15, 3 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, wp query, buddypress"
} |
Can a plugin still effect a site even after deletion?
I haven't been able to find an answer on whether or not this can happen. If there is a poorly built plugin that hasn't been updated in two years, and I make the poor decision to install it anyway - is it possible that even after complete deletion in the FTP this plugin could still be effecting my site? Has anyone ever dealt with something like this before and how did you fix it? I imagine I might have to check out the database if the plugin is causing this funky behavior, but I'm not sure where to start to rule this out. | Yes, a plugin that does not properly clean up after itself can continue to affect your site even after deletion. It can leave stuff behind in the database, or make alterations to your .htaccess file, which is probably the case in your scenario.
You might need to restore your .htaccess file - look here for help with that. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugins, errors"
} |
Handling single.php in Multisite
I'm using sub directories for my WordPress multisite, posts are controlled with single.php. How can instruct single.php to use a different header and footer file for the site in the sub directory?
I tried using get_current_blog_id but that didn't seem to work. For example:
$current_blog = get_current_blog_id();
if ($current_blog == 2) {
get_template_part('header', 'blog2');
} else {
get_header();
}
**Edit**
I was able to use in_category so this is my solution for now:
if (in_category('News')) {
get_template_part('header', 'blog2');
} else {
get_header();
} | I'm surprised `get_current_blog_id()` didn't work, since that's probably the best way to approach it. Always try doing a `var_dump( $current_blog )` to make sure you're testing for what you need. _Edit (19 Aug 2015): Also, triple check that you know which header you're expecting to see and that you're making the change you want in the right header file._
Alternately, consider making a child theme and replacing the header that way. That may be more maintainable over the long run, particularly if you plan on using unique headers for other sites.
Also, you can use `get_header( 'blog2' )` instead of `get_template_part( 'header', 'blog2' )`. Same result but the first way's a bit cleaner. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "multisite, templates, single"
} |
changing permalink gives 404 error for old links
I have changed the permalink from **Post name** to **Custom Structure**.
Earlier my blog links were like `www.website.com/blog-post-link` i want to change that to `www.website.com/my-articles/blog-post-link` so my **custom structure** permalinks looks as following and it does give me what I want
`
However all the old links are now giving 404 error `www.website.com/blog-post-link`
What can I do so that old links get redirected to the new link and does not give page not found error. I have 100s of blog post, i hope i dont have to manually do a redirect for each blog post.
I came across this question but it does not seem to work for me | Well, if your /%postname%/ part stays the same, .htaccess redirection can help you pointing old urls to the new ones like this:
RewriteEngine On
RewriteRule ^$ /my-articles [R=301,L]
Put this into your .htaccess file and it should redirect < to <
Beware that this will redirect everything, not only some post types or sth. like that. But .htaccess is very powerful and gives you lot of options to redirect or rewrite URLs. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, redirect"
} |
Display tab title as 'blog tagline | blog title'
I am currently displaying my title liek this `<?php wp_title( '|', true, 'right' ); ?>` it works fine for every page besides home page where tab currently says `Blog title | Blog tagline` is there a way I can change it to `Blog tagline | Blog title` ? Without affecting other pages. | Yes, you can include a check for `is_home()` or `is_front_page()` and return a different title based on that.
**Update:** TwentyEleven does it like this for example (lines 27 to 45). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, theme development, title, customization, wp title"
} |
Getting term description in single post template
I have custom posts called 'esitykset' and it has custom taxonomy 'tapahtumat'. Now I have been trying to get the description on one of the term in 'tapahtumat' taxonomy and i have no idea why it is not showing up. I have searching everywhere possible but couldn't find the solutions. Please help. My sode in the single-esitykset.php is below
<h2><?php the_terms( $post->ID, 'tapahtumat');
echo '<p>' . term_description( $post->ID, 'tapahtumat' ) . '</p>';
?>
</h2>
What is wrong with this code. Please help. | I think, you are looking for this
//to get all the terms for current post -
$terms = get_the_terms( $post->ID, 'tapahtumat' );
//get description of each term
foreach ( $terms as $term ) {
echo term_description( $term->term_id, 'tapahtumat' );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "templates, terms"
} |
woocommerce - how to get product link by id
i have 2 product_cat
`Product cat 1` id : 6
`Product cat 2` id : 8
in my index how to get product cat link with id or slug as:
`<a href="Product cat 1 (link)">Product cat 1(name)</a>`
`<a href="Product cat 2 (link)">Product cat 2(name)</a>`
Thanks | Product category is just a regular wordpress taxonomy. You can get the link like this:
echo esc_url( get_term_link( 6, 'product_cat' ) );
You can use slugs too:
echo esc_url( get_term_link( 'category-slug', 'product_cat' ) ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "woocommerce offtopic, categories"
} |
Query for user roles
How do I query for a specific user role?
if (is_user_logged_in() && user_role == "user") {}
The part I'm unsure about is user_role.
**Is there a way I can ask WordPress to check for a specific user role by name/string**? | You can check for specific user role using following code -
if (is_user_logged_in() && current_user_can('administrator')) {}
The function current_user_can() takes role name as parameter.
For more info - < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, functions, user roles"
} |
add class to background image
I'm trying to make a wordpress theme, using as framework the twitter bootstrap. On one page template I need to use the featured image as a background image, so I used this code:
<?php
global $post;
$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 5600,1000 ), false, '' );
?>
<div class="mainblogwrapper img-responsive img-center" style="background-image: url(<?php echo $src[0]; ?> ) !important; background-attachment : fixed;">
Everything looks great but I only have one problem. The image will not center for different screen sizes. ( **I see the whole image on 1920X1080 screen, but only the left of it on mobile screen** ).
I use the img-responsive and img-center classes but it is still not showing properly.
Check the website here <
How can I make the background image to show properly? How to make it responsive? | I have added the style "background-position: center center;" and it work perfectly!
So the new code will look like this:
<?php
global $post;
$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 5600,1000 ), false, '' );
?>
<div class="mainblogwrapper" style="background-image: url(<?php echo $src[0]; ?> ) !important; background-attachment : fixed;background-position: center center;"> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, post thumbnails, images, twitter bootstrap, custom background"
} |
Wordpress Redirecting Non Category Pages /page/nnn to their Canonical URLs
I seemingly to have a strange issue I have found in almost every other Wordpress site.
Suppose, you have set your Blog home to a static WP page `/myhome`. And you have a separate page for blog `/blog`.
Now, this works fine and should be:
/blog
/blog/page/2
/blog/page/3
/blog/page/4
But, for all other pages, e.g. `/about-us`, these links also work:
/about-us/page/2
/about-us/page/3
/about-us/page/4
And show the content of the `/about-us` page.
My problem is that `/about-us/page/2` should ideally redirect to `/about-us` (it's canonical URL) since there are no paginations in any other page except the `/blog`.
What am I missing there ? This seems to happen on almost all sites I have checked and is really frustrating from SEO point of view. | This is by design and intentional. WordPress rewrites have become increasingly complex over the years, and many plugins utilise the `page` endpoint for a page (usually with a template and custom query) - redirecting introduces a potential world of pain.
Long story short, it doesn't matter anyway. WordPress adds `<link rel="canonical />` for pages, so no need to worry over duplicate content.
**Update:** For localised situations where you want to disregard the potential risks, this will canonicalize all page URLS - note that it does not check if a page is actually paginated (i.e. with the `<!--nextpage-->` quicktag) and will break this feature if you use it.
function wpse_199180_canonical_pages( $wp ) {
if ( ! is_admin() && is_page() && isset( $wp->query_vars['paged'] ) ) {
wp_redirect( get_permalink( get_queried_object() ), 301 );
exit;
}
}
add_action( 'wp', 'wpse_199180_canonical_pages' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "url rewriting, htaccess, rel canonical"
} |
How to create "page" used for generating PDF?
I am new to wordpress but I do have some knowledge base in php.
I am developing custom theme for my Wordpress site. I also have a PHP file which generates PDF file based on GET parameters and it's located in theme's root folder - let's say it's called generate-pdf.php. And I want to create a link in some part of my website which refers to the script like this: "<
Is that possible without creating a page with slug "generate-pdf" in wp-admin and the page-generate-pdf.php?
I don't really want this script to be mentioned in administration.
Any suggestions? Thanks in advance. | Since it's a standalone script, you can just link to it directly and WordPress will be none the wiser. Just make sure you get the link right - if it's in your theme, it will be something like:
Don't hardcode the URL though, use the available template functions:
<a href="<?php bloginfo( 'template_url' ) ?>/generate-pdf.php">Generate!</a>
Of course if you want a "pretty" URL you can use the rewrite API. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions, routing"
} |
Add instructions For Media Library Uploads
I want my users to apply a filter in Photoshop every time they upload an image. Naturally, people are forgetful so I want to remind them of that in the Media Library Screen.
I search around which filter/action I could apply to get access to the content but, unfortunately, could not find anything. Is there any direct way to access the "Drop Files" text?
Thank you!
 {
?><h4>
<?php esc_html_e( 'Please Remember This And That! (pre-upload-ui)', 'wpse' );?>
</h4>
<?php
});
add_action( 'post-upload-ui', function() {
?><h4>
<?php esc_html_e( 'Please Remember This And That! (post-upload-ui)', 'wpse' );?>
</h4>
<?php
});
_You might want to adjust this further to follow the Admin UI style._
This will show up as:
.
<a href="<?php echo get_term_link( 42 ,'product_cat') ?>">Fine Art ... etc.</a>
Product category is just WP taxonomy, so there is plenty of functions to work with. In this case you have to know your product category ID (taxonomy term ID, actually). When editing category, you will find it in URL: .../edit-tags.php?action=edit&taxonomy=product_cat&tag_ID= **42** &post_type=product | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "php, woocommerce offtopic, archive template"
} |
How to get the uploaded image url in media_handle_upload()?
I am referring to this codex, <
There I can attach the uploaded image to the post as attachments by this :
`$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );`
But, I want to just get the `url` of the uploaded image, without adding the image as the post attachments.
How can I get that uploaded image url ? | You can get it with:
wp_get_attachment_url();
More info in the codex
In your example:
$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
$attachment_url = wp_get_attachment_url($attachment_id);
echo $attachment_url; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "uploads"
} |
woocommerce list product by id
i have product cat with id=5 and have 10 product
i show list 5 product by id as
$args = array( 'post_type' => 'product', 'posts_per_page' => 5, 'product_cat' => 5 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product;
**** loop code *****
endwhile;
wp_reset_query();
but is error code(don't show any product). if i change `'product_cat' => 5` by slug as `'product_cat' => 'slug_name'` is true.
How to show product by `id = 5`
Thanks | You should use "tax query" like this:
$args = array(
'post_type' => 'product',
'posts_per_page' => 5,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'terms' => 5,
),
),
);
Using taxonomy name (`product_cat`) as WP_Query parameter is deprecated. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
WordPress Admin Email
I am planning to build a WordPress site in which I will setup WooCommerce to sell products. I have created a test site before in which I used my personal email account (gmail) as admin email. Then I tested selling from the site. The problem I faced is that the order confirmation emails were going to spam folder of test client email. And the reason of marking as spam is that The message may not have been sent by [email protected].
How can I prevent the problem in my actual site? Should I start off with an email address such as [email protected] ? Or can I start with my personal email address as the admin email and then later change the admin email? Or can I just use my personal email as admin email and in the WooCommerce email setting I should enter [email protected].
To those who have already built and running WooCommerce sites, What is the best possible option regarding using emails?
Any suggestion will be greatly appreciated.
Thanks. | I would recommend to use the domain of the website as the email address. It's look more professional and formal. You can use no-reply email for sent messages related to the shop as [email protected] and for the main email address I would recommend to use [email protected].
You always can change the email address that you entered and test it but if the website is going to be active, better to chose one email address from the start. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "admin"
} |
Disable user registration password email
So, WordPress 4.3 has a new password system as we all know. Unfortunately, this new system has done away with the ability to **NOT** send new users an email.
My client was using a system where he sent a custom email to his clients, manually registering their emails, and then sending them an email with the login info with a custom message. We are aware that this new system is trying to be more secure, but this isn't working for the amount of control he would like.
I've found the following code in my search for a solution to turn these emails off, but I think they only turn off the notification emails for if a user's email is CHANGED for previously registered users, not when it's first created:
add_filter( 'send_password_change_email', '__return_false');
add_filter( 'send_email_change_email', '__return_false');
Does anyone know of any way to turn off these initial password emails sent after registration?
Thank you. | You can intercept this email before it is sent using the `phpmailer_init` hook.
By default, this hook fires before any email is sent. In the function below, `$phpmailer` will be an instance of PHPMailer, and you can use its methods to remove the default recipient and manipulate the email before it is sent.
add_action('phpmailer_init', 'wse199274_intercept_registration_email');
function wse199274_intercept_registration_email($phpmailer){
$admin_email = get_option( 'admin_email' );
# Intercept username and password email by checking subject line
if( strpos($phpmailer->Subject, 'Your username and password info') ){
# clear the recipient list
$phpmailer->ClearAllRecipients();
# optionally, send the email to the WordPress admin email
$phpmailer->AddAddress($admin_email);
}else{
#not intercepted
}
} | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 13,
"tags": "email, user registration, password, reset"
} |
Get meta value when the page is a blog archive
I'm using custom metaboxes on my pages. For example: header icon.
I created a page for the news on my site. I selected it as a blog archive page under Settings->Reading page. Unfortunately I can't get the meta values for this page.
When I create a page for the blog archive is it uses the index.php or the page.php?
I tried to read the metafields using the page id, but unfortunately `global $post; echo $post->ID;` returned only the id of the first post in the loop.
What is the best way to read meta values on a page, when it's selected as a blog archive? | `get_queried_object_ID()` will return the ID on the page for posts, or `get_queried_object()` will return the page object containing all its post fields.
Alternately, the ID of the blog page is stored in the option `page_for_posts`, which is internally how `get_queried_object` gets the ID of the post object to load. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field, loop, metabox, post meta, archive template"
} |
Register script in one plugin, and enqueue it in another
I need to register a script in one plugin and enqueue it in another. This is not working the way I expect it would. Am I missing something?
Plugin that registers script:
add_action( 'wp_enqueue_scripts', 'my_register_styles' );
function my_register_styles() {
wp_register_style( 'fontawesome', '//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css' );
//wp_enqueue_style( 'fontawesome' ); // This works when uncommented.
}
Other plugin to enqueue script:
add_action( 'wp_enqueue_scripts', 'other_register_styles' );
function my_register_styles() {
wp_register_style( 'style', PATH . 'assets/css/style.min.css' );
wp_enqueue_style( 'style' ); // Working as expected
wp_enqueue_style( 'fontawesome' ); // Currently not working!
} | Prioritize your actions, so the register_style function runs first. (notice the third parameter in the add_action function)
add_action( 'wp_enqueue_scripts', 'other_register_styles', 11 );
function other_register_styles() {
wp_register_style( 'style', PATH . 'assets/css/style.min.css' );
wp_enqueue_style( 'style' ); // Working as expected
wp_enqueue_style( 'fontawesome' ); // Currently not working!
}
The default priority is 10, so you just need to add 11 to other_register_styles. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, wp enqueue script"
} |
Update page (update-core.php) & Plugins page (plugins.php) revert to homepage
I am notified in my admin view of my Wordpress site that I have 1 available update for both the site and plugins (in my Network Admin Dashboard there '1' in red circles next to 'Plugins' and 'Updates')... But when I try to go to both the updates page & Plugins page, the homepage appears? The URL at that point is and respectively.
I can therefore never arrive at the true updates page, and cannot update my Wordpress or plugins. How can I get the updates or Plugins page to appear? | I've since found my own solution: Delete the .htaccess file in the Wordpress root directory. I've written more details in a post on my blog at cellepo.com. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, updates, network admin"
} |
Does Wordpress support template resources/custom fields
I'm pretty new to Wordpress development but say I want, based on my theme's page template I want to create a custom variable.
Ultimately the idea is to create a variable that appears as a field on the admin's post page. That variable can be called in my theme.
As a use case I have buttons on a site that I'd like different colors based on different pages. In making or editing a page I'd like to add a hex for the color in a custom field that inputs that code into the final html page.
I haven't found anything similar to this online. Any help would be appreciated. | Yes, **custom fields** or **meta fields** are part of WordPress. There are all information you need. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, custom field"
} |
How to call custom single post?
newbie here playing with php stuff, wanna learn. So the problem is. I have created custom posts and data from those is shown in a widget. Now i want to create custom single posts for those custom posts (dont get confused,yet).
I have single.php which shows my post and with
inside it i say if it's custom post show custom posts,else dont.
Now, thing is that i want to make a different single post look for those custom posts. I'v created a new file called match.php and inside i'v added stuff from single.php with some wanted modifications, and the only thing which remains is to call it i guess inside single.php but i dont know how.
So it would be inside single.php if there is custom post show it with match.php not with single.php, if there isnt show normal single.php
if needed my single.php is here < | Create `single-yourcostomposttypename.php` file in theme folder. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, loop, single"
} |
Jetpack JSON API configure button not showing
Installed fresh WP on my Hostgator - shared host plan. Installed Jetpack, connected to wordpress but can't make the JSON API to work. After activating there's no Configure button just deactivate button and i'm stuck. Thank you | You don't need to configure anything. As soon as you connect Jetpack to your WordPress.com account and activate the JSON API module, you'll be able to to use the API. You can double check that by running some test queries using the REST API Console here. You could also just try to load one of the endpoints in your browser, like so.
If you're still having issues working with Jetpack's REST API, I'd suggest contacting the Jetpack support team through this form, or in the Jetpack support forums. As mentioned in on-topic, it's best to use appropriate support channels for third party plugins and themes. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "api, json, plugin jetpack"
} |
Using ACF Custom Field value in a URL with do_shortcode()
I am using the ACF custom fields and video.js plugins and I want to add the custom field value inside the url for the youtube video that is inside of `do_shortcode()`
So far this is what I've come up with but it doesn't seem to work:
<?php
$thevideo = the_field('video');
echo do_shortcode('[videojs class="youtubevideo" youtube=" . $thevideo . '"]');
?> | Simply you need to replace `the_field('video')` with `get_field('video')`.
**Why?**
Because according to ACF documentation;
`get_field($field_name, $post_id, $format_value)`
> Returns the value of the specified field.
Whereas on the other hand
`the_field($field_name, $post_id)`
> Displays the value of the specified field. (this is the same as “echo get_field($field_name)”)
Hope this might help others as well. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field, shortcode, urls, advanced custom fields, variables"
} |
URL rewrite before template_redirect called
**Logic**
* I have a page template at `/blog` that contains a "public" blog.
* I have a page template at `/members` that is members area.
If a user enters the URL `/members/blog` I want to catch this in the `template_redirect` hook and load up a custom template that shows a "private" blog
**Problem**
Before `template_redirect` is called `/members/blog` is re-written to `/blog` so I can't load the private blog page.
There is nothing in the rewrite rules that says to do this. | So the problem was `redirect_guess_404_permalink` was detecting a 404 error and 'guessed' `/members/blog` to be `/blog`
My hacky solution was to hook into the status error check (Stop Wordpress from "guessing" redirects for nonexistent URLs) and if URL parts match then unset the guessed solution
function blog_no_redirect_guess_404_permalink( $header ){
global $wp_query;
if( is_404() ) {
// Get Request URL Parts
$url = parse_url($_SERVER['REQUEST_URI']);
$path = explode('/', $url['path']);
$path = array_filter($path);
$path = array_merge($path, array());
// If matches /members/blog then unset 'guess'
if (strtolower($path[0]) == 'members' && strtolower($path[1]) == 'blog') {
unset( $wp_query->query_vars['name'] );
}
}
return $header;
}
add_filter( 'status_header', 'blog_no_redirect_guess_404_permalink' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "url rewriting, templates, wp redirect"
} |
Tweak next_post_link for it to include thumbnail
I am using a fork from underscores.io, and there is this code:
next_post_link( '<div class="nav-next">%link</div>', _x( '%title <span class="meta-nav">→</span>', 'Next post link', 'nicosite' ) );
Wich prints the next post link,
How Can I use it (or alternatives) to include the post's thumbnail?
-edit-
Right now, I have
next_post_link( '<div class="nav-next">%link</div>', _x( '%title <span class="meta-nav">→</span>', 'Next post link', 'nicosite' ) );
$nextPost = get_next_post(true); $nextthumbnail = get_the_post_thumbnail($nextPost->ID, array(300,150) );
echo $nextthumbnail;
That it prints out the image, but this way I get outside the `a`... | If you have a look at what `next_post_link` you'll see that it takes a parameter `$link` as the second argument:
`next_post_link( $format, $link, $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' );`
Your parameter for this currently doesn't include the post thumbnail:
_x( '%title <span class="meta-nav">→</span>', 'Next post link', 'nicosite' )
So we need to add it like this:
$nextPost = get_next_post(true); // You are aware that this only checks for next posts in the same term, right?
if(!empty($nextPost) ){ //This is to check if there is a next post
$nextthumbnail = get_the_post_thumbnail($nextPost->ID, array(300,150) );
}else{
$nextthumbnail ='';
}
next_post_link( '<div class="nav-next">%link</div>', $nextthumbnail . _x( '%title <span class="meta-nav">→</span>', 'Next post link', nicosite' ) ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post thumbnails, next post link, previous post link"
} |
How to disable Wordpress blog folder
I've integrated Wordpress into my existing website and used WP JSON API to get the content from WordPress, but I don't want the WordPress itself to be available to my viewers.
When I refresh my website (`myWebsite.com/blog`), it appends a slash (`/`) and goes to `myWebsite.com/blog/`, which goes to the WordPress website itself and does not show mine.
How can I make sure that it does not append a slash to the URL and does not go to the WordPress theme when I refresh the page? | To clarify, `/blog` and `/blog/` are the same. The slash is added by the browser to properly structure the URL (best way I can explain it).
Your're trying to access two different pages with the `/blog/` slug. In this case, WordPress is overriding the blog link from your existing website and showing content from there.
What you'll need to do is set your WordPress site to a different location other than `/blog/`, such as:
`myWebsite.com/wordpress/`
Then, you will want to prevent unauthorized access to your WordPress site if someone got ahold of the link. You can use a simple plugin such as Force Login which require visitors to log in order to interact with the website. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "posts, api, blog, json"
} |
How to use parent theme functions in child theme functions.php file?
Parent theme required a foo.php file, and inside that file is a baz() function. I want to use that baz() function in functions.php of the child theme without recall foo.php file again. Are there any ways to do that? | If you can wait for the parent theme's `functions.php` to load you can hook to the `after_setup_theme` or `init` actions and do what you need there. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, child theme"
} |
How many queries are normal to execute on a WP site?
I use the following PHP code in my theme's footer.
<?php echo get_num_queries(); ?> queries in <?php timer_stop(1); ?> seconds.
Then I realized that about 140 to 210 queries are executed for each page. Is it normal or not? I use a caching plugin, does it help?
I'm using a shared hosting and _sometimes_ (not always) I get about 20 visitors in a second. | I wouldn't say it's not "normal", but it's above typical.
The common minimum of queries would go like:
* main query (set of posts)
* functionality (menus, widgets, etc)
* data (terms and such)
On a WP test data that would make something under 50 queries on home page. With object cache it will fall under 10 on repeat visits.
Without knowing your set up — yes, it is likely that you are requesting too many things and/or not caching results optimally.
However some sites _need_ to query a lot of things to, well, perform their function.
Roughly I would recommend to:
* dump queries and examine _what_ are they (Query Monitor plugin would be a start)
* add Object Cache back-end to server, see if it makes a difference (but it's a good idea to have in _any_ case)
* consider manual or semi-automated caching for code which makes queries (full page and/or fragment cache) | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "query, cache"
} |
datepicker value in mysql
I am using a plugin WP-Types for custom post types in which there is a option to create custom fields in which i created one date field for my requirement. Now what happens when i add any date into it .. It will store some kind of wired value ( for me ) in mysql as 14234233 something similar. I have attached a image which have those value in mysql.
Can you please tell me how i am able to achieve that value if i submit it from Jquery datepicker from frontend .
I am inserting values from front-end.
Thanks in advance !!!\[Attaced Image for reference]1 | It's a UNIX timestamp \- with PHP, you can use `date` to format it like so:
echo date( 'd/m/Y', $timestamp ); // day/month/year | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, customization, jquery, datepicker"
} |
shortcode get thumbnail size
How to get shortcode thumbnail size?
my code get shortcode thumbnail size in functions:
function thumb_medium( $atts, $content = null ) {
return wp_get_attachment_url( get_post_thumbnail_id( $post_id, 'medium') );
//or wp_get_attachment_url( get_post_thumbnail_id( $post_id, 'large') );
//or wp_get_attachment_url( get_post_thumbnail_id( $post_id, array(100,100)) );
}
add_shortcode("get_urlthumb", "thumb_medium");
but [get_urlthumb] always echo full url thumbnail as: `wp-content/uploads/2015/08/origin-image-upload.jpg`
Thanks | I think your code is very close, try to use `wp_get_attachment_image_src()` instead:
function thumb_medium( $atts, $content = null ) {
// return wp_get_attachment_url( get_post_thumbnail_id( $post_id, 'medium') );
global $post;
$thumb_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'medium' )[0];
if ($thumb_url) {
return $thumb_url;
}
}
add_shortcode("get_urlthumb", "thumb_medium"); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "shortcode, attachments, thumbnails"
} |
admin_url() do not retrieve the correct url in an subdirectory install
I have installed Wordpress locally in a subdirectory. I have the `admin_url( 'users.php' )` template tag in a plugin that retrieves the ` URL instead of the ` How to solve this?
**UPDATE**
This is the function where the above template tag is used:
function get_some_url() {
$full_url = add_query_arg( 'action', 'action-name', admin_url( 'users.php' ) );
$relative_url = str_replace( get_site_url(), '', $full_url );
return $relative_url;
} | I solved my problem by trying this (and it works!):
function get_some_url() {
$full_url = add_query_arg( 'action', 'action-name', admin_url( 'users.php' ) );
//$relative_url = str_replace( get_site_url(), '', $full_url );
//return $relative_url;
return $full_url;
}
This was tested in a localhost/subdirectory install and in a live install (not subdirectory). Now the URL is retrieved correctly. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp admin, directory"
} |
Wordpress mysql table double prefixes
Currently working on updating a wordpress website for a client of mine. The wordpress mysql database has double prefixes in it though.
The standard wp_ prefix and her own custom prefix for the tables. The custom prefix is currently being used. The wordpress install seems generator by installatron. Is it safe to remove all the wp_ prefixed tables or does wordpress still use those? | 1) In order to check what kind of prefix used by current installantion you can goto `wp-config.php` in a root directory and find line with `$table_prefix = 'PREFIX_HERE'`; variable
2) Backup the DB before making any action!
3) Additionally check if other tables with different prefixes/name_patters are not used by badly-written 3rd party plugins. They may not follow a good-practice:
> Do not hardcode the WordPress database table prefix (usually "wp_") into your Plugins. Be sure to use the $wpdb->prefix variable instead.
4) Right after this done you can drop all tables using a UI mysql admin panel or using more advanced way:
a. Generate a DELETE query programmaticaly:
SELECT CONCAT( 'DROP TABLE ', GROUP_CONCAT(table_name) , ';' )
AS statement FROM information_schema.tables
WHERE table_schema = 'YOUR_TABLE_NAME' AND table_name LIKE 'WORDPRESS-PREFIX_%';
b. Perform generated result. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "database, mysql, table"
} |
Save values generated via API as taxonomy terms
I'm using the IMDB Connecter plugin to grab meta data for movies and I'm wondering if I can save some of the information it generates as terms in a custom taxonomy that already exists.
What I want to do is to be able to save the "Director" and "Actors" information generated by the plugin as taxonomy terms. So for example, the values in the array generated by the `$actors` function would be saved as individual terms in my custom taxonomy `actors`.
This is my current code.
$imdb = get_field('imdb_id'); // IMDB movie ID is saved as a custom meta value
$imdbInfo = get_imdb_connector_movie($imdb);
$actors = $imdbInfo['actors']; // Gets an array of actor names
$director = $imdbInfo['director']; // Gets an array of directors
Is it possible to save these values as custom terms? | It's as easy as:
function wpse_199523_save_imdb_terms( $post_id ) {
if ( ! $imdb = get_field( 'imdb_id', $post_id ) )
return;
if ( ! $data = imdb_connector_get_movie( $imdb ) )
return;
if ( ! empty( $data['actors'] ) )
wp_set_object_terms( $post_id, $data['actors'], 'actors' );
if ( ! empty( $data['director'] ) )
wp_set_object_terms( $post_id, $data['director'], 'directors' );
}
add_action( 'wp_insert_post', 'wpse_199523_save_imdb_terms', 500 /* Ensure we run after ACF */ );
Refer to the codex on `wp_set_object_terms` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom taxonomy, api"
} |
add_editor_style is not working
I've reviewed various blog posts, stackexchange topics, etc, but can find no way to get add_editor_style() to work in WordPress 4.1.5.
Is anyone having any luck getting this function to work in recent versions of WordPress? Can I see how you've done it?
Currently I have something like the following in my functions.php file:
add_action( 'init', 'my_theme_add_editor_styles' );
function my_theme_add_editor_styles() {
add_editor_style('editor-style.css');
}
I see my editor-style.css referenced in the tinyMCEPreInit settings in the head (among the stylesheets assigned to 'content_css'), but there is otherwise no reference to editor-style.css in the head of the document.
PS -- The following also does not work:
function my_theme_add_editor_styles() {
add_editor_style('editor-style.css');
}
add_action('admin_init', 'my_theme_add_editor_styles' ); | I've now realized the code I posted works. I expected to see the stylesheet referenced in the head, but there is no such reference. It turns out the styles are being applied solely on the basis of the settings in tinyMCEPreInit.
In fact, this is all that's needed:
add_editor_style('editor-style.css'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "add editor style"
} |
is_404() - where does this get set?
Where does `is_404()` get set?
Looking at the source in query.php:
function is_404() {
global $wp_query;
if ( ! isset( $wp_query ) ) {
_doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
return false;
}
return $wp_query->is_404();
}
which just returns a value already set in $wp_query.
However, if I then set a breakpoint in `set_query_var` this never gets hit. | There is a dedicated method for it `WP_Query->set_404()`. From quick search through code it can be set in `WP_Query->parse_query()` or `WP->handle_404()` (note `WP`, not `WP_Query`!).
But it can (and sometimes does) get set on query externally, for example by plugin that needs to invalidate specific resource. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, 404 error"
} |
How to get the first letter from custom field?
I have a custom field 'first_name' created by ACF advanced custom fields. I use this code to get the value from the field: the out put would be something like Mark. What I need exactly is getting only the first letter from the first name. I tried to use
$string = the_field('first_name');
echo $string[0];
&
$string = the_field('first_name');
echo substr($string, 0, 1);
&
$myStr = the_field('first_name');
$result = substr($myStr, 0, 1);
echo $result;
but both methods give the full name not only the first letter. Any suggestions please? | Try this....
<?php
$string = get_field('first_name');
echo $string[0];
?>
I am not that much familiar with ACF. But my answer is based on their function reference here <
Hope this helps.
Sabbir H | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, custom field"
} |
Replace anchor tag with span tag
I have created my custom menu having many items and sub items, the markup is like this `<a href="#">Item</a>`but for parent element I need to replace anchor tag with the span tag having some class for styling purpose, only for my parent elements. It should be like this, `<span class="my-class">Parent Element</span>`. Can any one please guide me? | The following code added to your themes `functions.php` will do what you want.
add_filter( 'walker_nav_menu_start_el', 'my_walker_nav_menu_start_el', 10, 4 );
function my_walker_nav_menu_start_el( $item_output, $item, $depth, $args ) {
if ( empty( $item->url ) || '#' === $item->url ) {
$item_output = $args->before;
$item_output .= '<span class="my-class">';
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
$item_output .= '</span>';
$item_output .= $args->after;
}
return $item_output;
}
This should find all menu items with no URL or `#` as the URL and replace the link with `<span class="my-class">...</span>`.
This wouldn't specifically apply to parent menu items, but as long as you use a custom link and don't enter a URL (or you enter a `#`) for your parent menu items then it should work for you. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, sub menu"
} |
Plugin has no US english translation file
I'm trying to modify English translations for a The Events Calendar plugin but I'm not able to find the US English translation file. There is only British English. Please have a look:
 does not return true in multisite if user is Administrator but NOT Super Admin
I have a multisite WordPress installation set up, and have a user who is set to an 'Administrator' role on both sites. However, the function `current_user_can('Administrator')` does not return true when logged in as them, which I expected it to.
My user account, however, is an 'Administrator' on both sites, and _also_ a 'Super Admin' on the network, and the call returns true for me.
Why is this? Shouldn't the first user only be false if checking for 'Super Admin' and not just 'Administrator'?
If this is an issue, is there any other way that I can check if a user is set to the 'Administrator' role without being a 'Super Admin'? | I would agree that current_user_can('Administrator') should return true for the user. However, current_user_can is primarily intended to check for capabilities, which is generally a more robust check to be making.
I'd suggest something like this (untested):
if ( current_user_can( 'activate_plugins' ) && ! current_user_can( 'update_core' ) ) {
//...
}
So this is checking if the current user can activate plugins but cannot update core. This should return true for Administrators whilst returning false for Network Admins - as on multisite update_core is reserved for Network Admins. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "multisite, admin"
} |
how to make a profile entry read only except for site managers
I have set some extra profile fields set in buddypress (under users profile fields), and I want to make sure they are read only with the exception of site administrators.
How do I accomplish this?
Thank you. | You can hide profile fields on the edit screen from everyone except site admins - therefore they can only be edited by site admins. They will still be visible on the public profile screen. You can get the field id by looking at the url in wp-admin when you edit that field, or just rolling over the edit button. Add this function to your child-theme functions.php or bp-custom.php
function arcee_hide_profile_fields( $retval ) {
if( is_super_admin () )
return $retval;
if( bp_is_profile_edit() )
$retval['exclude_fields'] = '3,43,253'; //field ID's separated by comma
return $retval;
}
add_filter( 'bp_after_has_profile_parse_args', 'arcee_hide_profile_fields' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "users, buddypress, profiles"
} |
Where can i find wordpress auto update code flows?
I want to see how WordPress auto update works in code . which WordPress file or function performs auto core update? I have read
I have understood theoretically. but want to look code ! | The code you are seeking for is located in the `wp-admin/includes/class-wp-upgrader.php`. There is a bunch of classes regarding all updates. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugin development, functions, code, automatic updates"
} |
Action hook with wrapper html
I want to add a space for a banner across the top of my WooCommerce Category pages, but i'm trying to figure out how to add some markup that will wrap the action.
In my archive-product.php I have the following code;
<?php
do_action('category_promo_header');
?>
Basically, if a Category has the 'category_promo_header' Action Hook Name set, I would like to output the content and wrapped in some additional markup such as;
<div class="row">...</div>
I want to do it this way so that the client doesn't have to remember to add the additional makeup every time. Do I need to do this in the functions.php or can i place some conditional in the archive-product.php?
Thanks. | You want the `has_action()` function.
add_action(
'category_promo_header',
function () {
echo 'hi there';
}
);
if (has_action('category_promo_header')) {
echo '<div>';
do_action('category_promo_header');
echo '</div>';
}
Comment that `add_action` and you should see that nothing is printed at all. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "hooks, actions"
} |
Automatically add tag if a checkbox is checked
I'm looking for a simple function to automatically add a specific tag to a post if a checkbox is checked.
For example: When creating a post there is a checkbox that says:
"Add example tag to post"
If you check it, the post will be given an "example" tag.
I have the checkbox set up, it's just adding the tag when checked which is causing me some difficulties.
Here is the function in my child theme function file that is causing the problem:
* * *
add_action( 'wp_set_object_terms' , 'add_example_tag');
function add_example_tag() {
global $post;
$example = get_post_meta( $post->ID, '_example', true );
if ( $example ) {
wp_set_post_tags('example', true );
}
}
Any help is greatly appreciated.
Cheers. | If I understand what you want I would call it on the save_post hook: <
So the code would be something a little like:
function wphuyeh8_save_post_tag( $post_id, $post, $update ) {
// If example is set and not false
if($_REQUEST['_example']):
// set the tag
wp_set_post_tags( $post_ID, 'example', true );
else:
// remove the tag if the checkbox is not checked
wp_remove_object_terms( $post_id, 'example', 'post_tag' );
endif;
}
add_action( 'save_post', 'wphuyeh8_save_post_tag', 10, 3 );
Though this is untested, and taking a second glance it will try and remove the tag on every post save unless it is checked so you may want to add in some checking for a post type or something. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, tags"
} |
Change Password Strength Indicator names?
Is it possible to change the labels for "Weak, Medium, Strong" etc... in the Password Indicator that's used in the user profile? I've been asked to change the word "Weak" to "OK" since this level of passwords is acceptable for our subscribers. Is there a filter I can hook into? | I was able to fix it with this method. Is this good/bad? It's working, but I'd be interested in feedback in case this could have unexpected consequences.
add_filter('gettext', 'translate_text');
add_filter('ngettext', 'translate_text');
function translate_text($translated) {
$translated = str_ireplace('Very Weak', 'Bad', $translated);
$translated = str_ireplace('Weak', 'OK', $translated);
return $translated;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "filters, password"
} |
how to get attached file url for current post?
Trying to get the attachment file url for current post, using this code:
if ( is_singular('post') ) {
$args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' => null, 'post_parent' => $post->ID );
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo wp_get_attachment_url( $attachment->ID );
}
}
else {
}
}
the problem is: this code displays the url of a file attached to another post 'author' which is a child post in relationship by ACF advanced custom fields plugin. I need to display the url of the file attached to current post and not to the child one. any suggestions please? | try get_pages with
'child_of' => get_the_ID(),
'parent' => get_the_ID(),
If you need i can post full code
EDIT :
if ( is_singular('post') ) {
$args = array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_status' => null,
'parent' => $post->ID ,
'child_of' => $post->ID,
'sort_order' => 'desc'
);
$attachments = get_pages( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo wp_get_attachment_url( $attachment->ID );
}
}else {
}
}
I hope this code help you | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, urls, attachments"
} |
Woocommerce set single city to sell to
In Woocommerce settings, if "sell to specific countries" is selected as single country, the checkout page shows the country and there is no option to select/change that. How is it possible to achieve the same for city field?
.val('Mumbai').attr('disabled','disabled');
You just need to add this line such that it is execute on Checkout page. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
Load same sidebar multiple times
I came across a very different scenario where I had to use `get_sidebar('recommendations')` multiple times on one page. But it works only one time.
It works multiple times only when I use `include('sidebar-recommendations.php')` but I want to go with standardize way in WordPress.
I searched in the code but couldn't find the reason why It doesn't work multiple times? | You can't.
get_template() function has a protection against this.
You will have to use include(). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "sidebar"
} |
What is singular.php?
From 4.3 we have a new template, `singular.php`. I tried to understand what is it, but I didn't get it. :)
The `page.php` for pages. The `single.php` for every post types. If we have `single-[post-type].php` we can use a specific template for the custom post type.. so why we need `singular.php`? | It's the nature of the WordPress template hierarchy \- point being, if you _don't_ have a `page.php`, it will use `singular.php`, same if you don't have `single.php`, it will _fallback_ to a template lower in the hierarchy.
Ideal for themes that have the same layout for posts/pages, instead of having duplicate code in each respective template. | stackexchange-wordpress | {
"answer_score": 17,
"question_score": 14,
"tags": "custom post types, page template, single, template hierarchy"
} |
Wordpress 4.3 broke meta redirect (with url params plugin)
I'm using the plugin URL Params (homepage) in order to send an URL to a page and after three seconds redirect the user to that page. Unfortunately Wordpress 4.3 broke that functionality.
This is how it was done:
<META HTTP-EQUIV="Refresh" CONTENT="3; URL=[urlparam param="link"]">
The redirect only redirects the user to <
A work around is putting a link and placing it like this but then I loose the auto redirect.
<a href='[urlparam param="link"]'>
Does anyone know how to rewrite the meta tag so that the redirect could work? | You need to allow the content attribute of a meta tag to contain a shortcode, eg in your "functions.php" add:
add_filter( 'wp_kses_allowed_html', function ( $allowedposttags, $context ) {
if ( $context == 'post' ) {
$allowedposttags['meta']['content'] = 1;
}
return $allowedposttags;
}, 10, 2 );
and then your original **(without the quotes in`param=link`)**
<META HTTP-EQUIV="Refresh" CONTENT="3; URL=[urlparam param=link]">
should work. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, redirect"
} |
What is the code to get the download link for a product in WooCommerce?
I'm trying to add the direct download link of a product to a button, but I'm stuck.
What I tried is this
<a href="<?php echo $product->downloadable_files; ?>">Download</a>
And of course it didn't work.
What is the proper code to get the product's download url? | Here is the code to get the download link for a downloadable product in WooCommerce.
$downloads = $product->get_downloads();
foreach( $downloads as $key => $each_download ) {
echo '<a href="'.$each_download["file"].'">Download</a>';
} | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 5,
"tags": "post meta, woocommerce offtopic"
} |
reply to comment excerpt instead of author in comment title
One can reply to a comment using `Reply` link, below each comment item in comments list.
According to codex, by clicking that link and using `comment_form_title` function like this:
$replytext = 'Leave a Reply to %s'; // %s = author
comment_form_title( $noreplytext, $replytext, $linktoparent );
You can have a comment form title as `Leave a Reply to [author's name]`.
I would like to find a way in which you have this output instead:
**Leave a Reply to [comment's excerpt]**
where comment's excerpt is the comment's first few words. | Finally I found a way and I am posting it here to address any further requests for such a workaround.
You may add a customized version of `comment_form_title` function to your theme's `functions.php` file and call it in your theme's `comments.php` file.
function my_comment_form_title( $linktoparent = true ){
global $comment;
$noreplytext = __( 'Leave a Reply' );
$replytext = __( 'Leave a Reply to %s' );
$replytoid = isset($_GET['replytocom']) ? (int) $_GET['replytocom'] : 0;
if( 0 == $replytoid ){
echo $noreplytext;
}else{
$comment = get_comment( $replytoid );
$excerpt = get_comment_excerpt( $replytoid );
$title = ( $linktoparent ) ? '<a href="#comment-' . get_comment_ID() . '">' . $excerpt . '</a>' : $excerpt;
printf( $replytext, $title );
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "comments, comment form, comments template"
} |
How can I display and excerpt of all pages with a meta_key and meta_value on index.php?
I need to create some pages with a custom field called categoria-pagina so I can display a list of these pages and their excerpt on my theme's index.php. I have already tried the code bellow, but if I use the args it doesn't display anything.
<?php
$args = array(
'meta_key' => 'categoria-pagina',
'meta_value' => 'programas'
);
$pages = get_pages($args);
foreach ($pages as $page) {
echo "<p>$page->post_title</p>";
}
wp_reset_postdata();
?>
;
?>
What does a `print_r($args)` return for you ? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, pages"
} |
insert_with_markers() WordPress & htaccess help
I'm trying to develop a plugin which adds a single line to the .htaccess file generated by WordPress.
The problem is that one of the WP generated lines override my rule, and via the "insert_with_markers()" function, I have not found a way to specify a position so I could prepend my line instead of appending it as currently is happening.
The first line of code is the auto generated WordPress line, and the second one is the one I'd like to have working.
RewriteRule . /dev/index.php [L]
RewriteRule ^article/([/_0-9a-zA-Z-]+)$ [R=301,L,NC]
The way I see it there's 2 possibilities here:
A) Somehow specify where the insert_with_markers() places the new line of code, or
B) Modify my RewriteRule to work together with the WordPress generated one.
I hope you can point me a step or two closer to the right path.
Thanks! | I would suggest an alternative route: the rewrite API - did you know it supports external URLs*?
function wpse_199898_add_htaccess_rule() {
// No need for the caret "starts with", WP will add it
add_rewrite_rule( 'article/([/_0-9a-zA-Z-]+)$', ' [R=301,L,NC]' );
}
add_action( 'init', 'wpse_199898_add_htaccess_rule' );
*Almost. We just need a fix for WP's quirky path prefixing:
function wpse_199898_fix_htaccess_rule( $rules ) {
return str_replace( '/ ' $rules );
}
add_filter( 'mod_rewrite_rules', 'wpse_199898_fix_htaccess_rule' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "htaccess"
} |
New User ID not working in custom function with user_register hook
I'm adding data to a table whenever a new user registers on the site.
add_action( 'user_register', 'auto_follow_admin', 10, 1 );
function auto_follow_admin() {
global $wpdb;
$wpdb->insert( 'wp_um_followers', array(
'time' => current_time( 'mysql' ),
'user_id1' => 1,
'user_id2' => $user_id
)
);
}
Everything works fine apart from the the new $user_id which isn't being passed to the query.
The stored data after it's run looks like this :
time : 2015-08-27 14:08:32
user_id1 : 1
user_id2 :
Is **global $wpdb;** resetting the user_id? | Because you need to give your function a parameter:
function auto_follow_admin( $user_id ) {
// Now you can use $user_id, which is passed to the function from the hook caller
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "users, hooks, wpdb, user registration"
} |
Getting "too many redirects" when using wp_redirect for attachment page
Code comes from the codex:
<?php wp_redirect( get_permalink( $post->post_parent )); exit; ?>
I added the above, in an empty attachment.php page. When I visit an attachment page (eg. < I get the error:
"This webpage has a redirect loop ERR_TOO_MANY_REDIRECTS"
Why?
UPDATE:
Based on the answer given, I updated my code to:
if($post->post_parent != 0):
wp_redirect(get_permalink($post->post_parent));
else:
wp_redirect(get_permalink(2));
endif;
exit;
That way if the post_parent == 0, it will go back to the home page. I don't know if I should be catching for anything else. But this seems to work.
Thanks Ignat B. for explaining what was going on. I have a few attachments that have post_parent = 0. And it just happened that the link I was trying out was one of them. | Considering WordPress Codex, and WordPress Template Hierarchy \- attachments stores as post records.
Your code is making a loop redirection to the same page. The most reasonable case is:
Your `$post->post_parent` equal to `0`. If you'll make a `var_dump(get_permalink($post->post_parent));`, youll notice that the output would be the same page url. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "attachments, wp redirect"
} |
Get array of current post term ID's
I'm creating a little "Related posts" section on a site and I'm doing it based on terms in a custom taxonomy called "director".
How can I get an array of term ID's for the current post so that I can use them in a custom WP_Query array? | To get the attached term IDs, use `get_the_terms()` and `wp_list_pluck()`:
if ( $terms = get_the_terms( $post, 'director' ) ) {
$term_ids = wp_list_pluck( $terms, 'term_id' );
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "wp query, custom taxonomy, terms"
} |
What is comment_karma?
While doing a `var_dump` on the `$comment` object, I see there is a `comment_karma` property. What is that? | You get the comment_karma property because there is such a column in the comments table. It is meaningless and AFAIK was never used for anything except for maybe some random spam prevention plugin. It is there just for backward compatibility and because no one thinks that removing it will improve anything in a measurable way.
You can use that field if needed, but it is probably a better idea to use your own meta field. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 4,
"tags": "comments"
} |
Combining similar shortcode functions?
function customfield_1_shortcode( $atts ) {
if ( get_post_meta( get_the_ID(), 'customfield1', true ) ) {
$customfield = get_post_meta( get_the_ID(), 'customfield1', true );
return "html stuff";
}
add_shortcode( 'customfield_1', 'customfield_1_shortcode' );
function customfield_2_shortcode( $atts ) {
if ( get_post_meta( get_the_ID(), 'customfield2', true ) ) {
$customfield = get_post_meta( get_the_ID(), 'customfield2', true );
return "html stuff";
}
add_shortcode( 'customfield_2', 'customfield_2_shortcode' );
?>
I can use [customfield_1] to output customfield1 stuff, and [customfield_2] to output customfield2. What is the best way to combine these two or more functions like these (customfield_3, customfield_4 etc.) to achieve the similar effect? | I don't know exactly what you are trying to do but perhaps something like this:
function customfields_shortcode( $atts ) {
if (!empty($atts['field']) && get_post_meta( get_the_ID(), $atts['field'], true ) ) {
$customfield = get_post_meta( get_the_ID(), $atts['field'], true );
return "custom field >> $customfield << custom field";
}
}
add_shortcode( 'mycustomfields', 'customfields_shortcode' );
echo do_shortcode('[mycustomfields field="customfield_1"]');
One shortcode will handle all of your custom fields. Just pass in the field you want as an attribute (argument). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "shortcode"
} |
Why I am getting Parse error: syntax error when I use 'wp_is_mobile'?
I am getting following error message :
Parse error: syntax error, unexpected '{' in /home/otcpaneluser/public_html/mytheme/header.php on line 1
My header.php have very simple lines of code. Those are:
<?php
if ( !wp_is_mobile() ) { // desktop header
echo 'I am the desktop header';
}
else {
echo 'I am the mobile header';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "
<html xmlns="
<meta name="google-site-verification" content="lePo6W0p7rXhyUR2Yd21QNuJey6t9b240pkJlPbZJe4" />
<head></head>
<body>....</body>
</html>
Why does this happen? How can I solve this?? | You should not be executing anything before your `DOCTYPE` tag. That will all be invalid code and is also the issue leading to your error.
In general, any output like above should be done after the `<head></head>` tags, although some prefer to hook into the `wp_head` hook to execute functions like your code. I do prefer however to move such code after the closing `head` tag.
So your solution would be to move your conditional code to just after the closing head tag | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "mobile, custom header"
} |
When can you get current page ID and initialize hooks right after?
I'm developing a plugin and need to know on what page user is and then add specific hooks and filters for that page.
And my problem is that `is_page()` and `the_ID()` doesn't work outside of `wp`, `wp_loaded`, `init` actions, but if i use these actions then i can't initialize hooks because for them to work properly they must be added before those actions.
So my question being, is there any hook from witch i can call `the_ID()`, get a proper result **and then** add another hooks for that page? Or is it possible **only** using PHP's `$_SERVER['REQUEST_URI']`? | The earliest safe hook to get post information is the `template_redirect` hook. All the hooks in question runs before Wordpress has setup postdata, so any post info are still unavailable at that point.
The globals like `$wp_query` and `$post` will still contain no data, that is why your efforts returns nothing.
## EDIT
Extra info as per comment by @TheDeadMedic
> Actually `wp` is an earlier, still-safe hook - just make sure to use `get_queried_object()` instead of relying on `$post` global | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 6,
"tags": "plugins, plugin development, hooks, actions, wp enqueue script"
} |
Adding HTML within an image title attribute
I am using some jquery which applies an overlay on an image on hover. The script uses content from the image's title attribute to display over the image. When I tested this locally, it seemed to work, and I could style the text within `title=""` however, I'm now trying to get it working in WordPress, and it doesn't seem to let me style the text within the title attribute.
<img src="img.png" title="<h1>Title heading</h1><hr><h2>Title sub heading</h2>" | First of all i'd recommend you stop using `title` attribute for html container purpose:
> Image title (and the element name speaks for itself) should provide additional information and follow the rules of the regular title: it should be relevant, short, catchy, and concise (a title “offers advisory information about the element for which it is set“). In FireFox and Opera it pops up when you hover over an image
In order to get things works you can use `data-` attribute (very good "intermediate" article about data-attribute with example how to use)
Considering [[Can data-* attribute contain HTML tags?]]( it's valid to use `data-` attributes with HTML, and, as recommended under the refference above - take into account character escape. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "images, css, html, title, customization"
} |
Disabling HTTPS redirection for migration
I migrated a WordPress 4.3 site from Register.com to MediaTemple today and found that the forced SSL is causing issues for the staging URL.
In order to try again I have (on the live Register.com site)
* Disabled plugin 'WordPress HTTPS'
* Removed `define( 'FORCE_SSL_ADMIN', true );` from wp-config
* In General Settings replaced https w http for URLs and saved
* Saved permalinks just in case
* verified that .htaccess is not redirecting to https via mod_rewrite
Tried logging out and accessing site and still get redirected from http to https.
Assuming my predecessor has not done anything truly crazy what am I missing there? Where should I look? | In the active theme I found the redirection in header.php
Once commented out the issue was resolved.
if($_SERVER["HTTPS"] != "on")
{
header("Location: . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
exit();
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "redirect, ssl"
} |
Custom page template with custom fields
I need to create a page template that has an image and text with a common style. The image url must be set using a custom field (or something like it) and left aligned to the page title and content.
How can I create this custom page template and use a custom field to set the image url? | Create a Page_YourCustomName.php . copy page.php content to your new file. add the following code to first Line :
<?php /* Template Name: Your Custom Name */ ?>
Once you upload the file to your theme’s folder , go to the Page > Edit screen in your admin dashboard.
On the right hand side under attributes you’ll see template. This is where users are able to access your page templates.
then you would add metabox to your page/post in admin panel for use it to your template . please read this link to ( How to create metabox and use it ) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "theme development, custom field, page template"
} |
Why would media_sideload_image() not work locally?
I designed a theme for a client that sideloads an image returned from an API. It has always worked and it's still working on their live website.
My staging environment _used_ to be a separate account on the same server. It was accessible online but password-protected and sideloading images always worked there as well. Today I created a local staging environment using VirtualHostX. Everything on the website works as expected, _but sideloading doesn't._
* Nothing in my source has changed.
* The WordPress installation is a direct clone (configuration and build numbers are identical)
* I've verified that my AJAX response is returning an image URL, but the image doesn't even make it into the media library.
Before I spend too much time diagnosing this I thought I'd ask the obvious: is there a reason `media_sideload_image()` wouldn't work locally? | Ah, this is silly, but it turns out there was a **very** obvious reason why `media_sideload_image()` wasn't working. My `wp-content` folder had the wrong the permissions from when I transferred it to my local environment and I wasn't able to upload anything. Changed the permissions and it's working fine. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "uploads, media, post editor"
} |
Admin sidebar items overlapping in admin panel
Before to report this to wordpress I would like to know if it's just me or it's actually a bug. I noticed also another user that asked on the wordpress forum but he hadn't an answer for that: <
And the same is here:  extensions all deactivated | This is a known issue.
The current fix (which may also make it into core) looks like this:
add_action( 'admin_enqueue_scripts', 'chrome_fix' );
function chrome_fix() {
if ( strpos( $_SERVER[ 'HTTP_USER_AGENT' ], 'Chrome' ) !== false ) {
wp_add_inline_style( 'wp-admin', '#adminmenu { transform: translateZ(0) }' );
}
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "admin menu, bug, google chrome"
} |
Adding custom image size to the media image editor
I'm trying to give a more complete experience to my WordPress backend users and let them edit the custom image sizes I have added to my theme.
I added this to my `functions.php`:
add_image_size( 'new_image_size', 500, 500, true );
I would like the new size to be available here:
 {
add_image_size( 'wide-image', 900, 0);
}
add_action( 'after_setup_theme', 'my_setup_image_sizes' );
// add custom size to editor image size options
function my_editor_image_sizes( $sizes ) {
$sizes = array_merge( $sizes, array(
'wide-image' => __( 'Image 900px wide' )
));
return $sizes;
}
add_filter( 'image_size_names_choose', 'my_editor_image_sizes' );
**NOTE** You will have to regenerate thumbnails if you would like to define new image size for existing images
**NOTE 2** Base image size has to be greater than dimensions specified inside `add_image_size` function | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "images"
} |
Categories dropdown with all values selected using wp_dropdown_categories
I'm using this code to get a dropdown list of categories, but **all options are marked as selected**. Therefore, the last option is the one that is displayed as selected by default.
<?php wp_dropdown_categories(
array(
'class' => 'form-control',
'show_option_none' => 'Search by category...',
'hierarchical' => true,
'depth' => 1,
'hide_empty' => true,
'exclude' => 1,
'orderby' => 'NAME',
'value_field' => 'slug',
)
); ?>
I also tried with the following parameter, but it didn't work.
'select' => 0
How can I prevent the selected attribute to be assigned to all items? | Add this parameter:
'select' => false
The solution is in the Wordpress Codex Function Reference for wp_dropdown_categories:
> The default value for the selected parameter is 0, but this can cause a dropdown with all terms marked as selected. To fix this, set the selected parameter to false, rather than 0. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, dropdown"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.