INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to get posts with a metadata numeric key greater than X?
I'm trying to add a "Highlighted" section for each category on my website. This will be located in a page, using a shortcode. I'm going to add a new post metadata key which will be a number from 0 to 100. Each "Highlighted" section will list the posts in that category which have a score higher than 50, in descending order of score.
Looking in the WordPress Codex, I saw that get_posts accepts "meta_key" and "meta_value" as arguments. However, they seem to be specific values, whereas I would like to add a "greater than 50" condition for the "meta_key".
How would one get those "greater than 50" posts? | This kind of _meta query_ in `WP_Query()` or `get_posts()`:
'meta_query' => [
[
'key' => 'score',
'value' => 50,
'type' => 'numeric',
'compare' => '>=',
],
],
would generate the following SQL `WHERE` part:
wp_postmeta.meta_key = 'score' AND CAST(wp_postmeta.meta_value AS SIGNED) >= '50'
This kind of _ordering_ :
'orderby' => [
'meta_value_num' => 'DESC',
'title' => 'ASC'
],
would generate:
ORDER BY wp_postmeta.meta_value+0 DESC, wp_posts.post_title ASC
If we use the syntax defined here, with the meta query array index as `score_clause`, then
'orderby' => [
'score_clause' => 'DESC',
'title' => 'ASC'
],
would generate:
ORDER BY CAST(wp_postmeta.meta_value AS SIGNED) DESC, wp_posts.post_title ASC | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom field, post meta"
} |
wpdb get_row database query inquiry
Is this the right way to use get_row with a select *?
$_crds = $wpdb->get_row($wpdb->prepare(" SELECT * FROM `mailers` WHERE `id` = %d", $_GET['caId'] ));
$_zipcodes = $_crds->zipcodes;
$_maildate = $_crds->maildate;
Is that the right way to pull the values from the database? I have a lot of records in that table I need to pull, so wanted to do it in one db pull...
but my code appears to not be working.
-Rich | For Placehold to work, you should use $wpdb->query like:
$wpdb->query(
$wpdb->prepare( "
SELECT * FROM mailer
WHERE id = %d
",
$_GET['caId']
)
);
However in my opinion, the best option is to simply validate the get-parameter and than use it in $wpdb->get_results , like:
$catId = $_GET['caId'];
if(is_numeric($catId)){
$_crds = $wpdb->get_results(" SELECT * FROM mailers WHERE id = $catId");
foreach ($_crds as $_crds) {
$_zipcodes = $_crds->zipcodes;
$_maildate = $_crds->maildate;
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wpdb, get row"
} |
How do I link the side images?
This is my site: <
I want to link the background image to another page.
This is the code I have so far:
body.boxed-layout {
background-image:url(<?php echo get_site_url(); ?>/wp-content/uploads/2016/01/bg4-1.jpg) !important;
background-size:cover !important;
background-repeat:no-repeat !important;
background-position:center center;
}
The CSS is inline. How would I go about linking the background image to a different page? | I took a look at your site, and are you sure you dont want to make the .wrapper clickable? boxed-layout is your whole site, so if you made that clickable the whole site would be a link.
However, if I look at your question, the answer would be to use jQuery.
<script>
$(".body.boxed-layout").click(function(){
window.location = "
});
</script>
Note that this probably is not what you want!
Are you sure you don't want to make the < clickable? | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -4,
"tags": "php, css, html"
} |
How to use copy() function and paste file in /wp-content/themes directory
copy("
currently it is pasting file in wp-admin folder, Is there any way I can copy .zip file to /wp-content/themes directory.
Thank You :) | So I found the solution:
copy(" get_theme_root() . "/themenew.zip"); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php, plugin development, theme development"
} |
Dynamically change feature image in customiser
For this client's Website I am making on their homepage there is a section called featured products with images showing off the product. Currently I have to update these images manually through my `front-page.php` file but I don't want the client to have to do this, I need a custom section in the customiser called something like `featureImages` and here he can upload his own image that then updates on the front-page. There would have to be 4 upload sections like:
`featureImage-1` `featureImage-2` `featureImage-3` `featureImage-4`
Then when he uploads a file to either one of them it replaces the currently one with the one he has. I've seen this on some themes but I just don't know how they do it.
I've tried searching for this but I don't really know how to put it into words for Google to give me a result.
I apprentice any help or if you could point me in the right direction if this has been asked before :) | The customizer has a special control for file uploads. Assuming that you already know how the theme customizer works, you would have to add four controls in this fashion:
$wp_customize->add_control(
new WP_Customize_Upload_Control(
$wp_customize,
'wpse215632_image_1',
array(
'label' => __( 'First image', 'wpse215632_theme' ),
'description' => __( 'More about first image', 'wpse215632_theme' ),
'section' => 'wpse215632__section_id',
'settings' => 'wpse215632__setting_id',
) )
);
Now, you can retrieve the image in your template with `get_theme_mod('wpse215632_image_1')`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "php, functions, theme development, theme customizer"
} |
If post has custom field then display css-class
I would like to display a different icon in an `i` tag if a post has a certain key of a customized field. In my example `Preis`:
<i class="(get_post_meta(get_the_ID(), 'Preis', true) != '' ? echo "fa fa-check" : echo "fa fa-times")">
However, as output I get nothing back.
Any suggestions, what is wrong with my `IF-ELSE` structure? | You most probably ran into problems with escaping code and HTML from each other.
Try this (added line breaks just for better readability):
<i class="
<?php
echo (get_post_meta(get_the_ID(), 'Preis', true) != '') ?
'fa fa-check' : 'fa fa-times';
?>
"> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, plugins, php, posts"
} |
Custom Widget options in theme
I want to reprogram my first sketch of our theatre club page in wordpress but until now I only have basic knowledge of creating wp pages. As I want the theme to be as customizable as possible I want to add options to the widget according their appearance.
My Sketch (That was developed using a node.js framework) is live under this domain: <
I want my theme to show a big widget area on the start page and each widget needs to get information about how it should be displayed, that generate different classes of the corresponding widget.
is it posible to add options to widgets (that are not written by me) from my theme? | It is possible. Look at the in_widget_form hook. Saving to the instance is the widger_update_callback hook. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development, widgets"
} |
Unable to give correct path in wordpress
Suppose their is a wordpress theme say zumper. Apart from files such as footer.php, header.php their are other folders such as layouts inc
suppose I have a file america.php in layouts folder and york.php in inc folder
what is the correct path and correct way to include york.php from inc folder to america.php, which is in layout folder
Summarizing - america.php - Layout Folder york.php - inc folder
I want to include york.php in america.php what is the correct way specially the correct path? | Use:
`get_template_directory()` and or `get_stylesheet_directory()`
E.g. in `zumper/layouts/america.php`
<?php
include get_template_directory() . '/inc/york.php';
//etc...
Note:
### get_template_directory
> Retrieves the absolute path to the directory of the current theme.
### get_stylesheet_directory
> Retrieve stylesheet directory Path for the current theme/child theme.
So if your theme is a child theme and or you want to provide the ability for a child theme to override your parent include then use the latter. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development"
} |
how to change link of some wordpress pages
I've made templates for the pages of my wordpress site such as: singup,signin,suggestions. Default wordpress pages link is as follows:
`doamin.com/signup/` or `doamin.com/signin/` or `doamin.com/suggestions/`
I want to just link to this page to be changed as follows:
`doamin.com/panel/signup/` or `doamin.com/panel/signin/` or `doamin.com/panel/suggestions/`
**Using what code can do this?** | Create a **blank page** and name it **panel** then go to your created signup template and select parent page **panel**. Its just below Publish->Page Attributes.
/*Add noindex to this page (Add to functions.php)*/
function add_noindex_tags(){
# Add noindex to page.
if( is_page('panel') )
echo '<meta name="robots" content="noindex,nofollow">';
}
add_action('wp_head','add_noindex_tags', 4 ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "functions, pages, hooks, page template"
} |
How to Prevent deleting user accounts in WordPress Back-end?
I have tried to find similar question. And I have not get any existing one. I want to prevent deleting administrators from the back end users table. only two admins can delete all users, But other admins cant delete all other administrators. I have tried this code. But if i go with direct url parameters, its allowing me to delete the user.
function kv_admin_deactivate_link($actions, $user_object) {
if($user_object->ID == 1 || $user_object->ID == 2)
unset($actions['delete']);
return $actions;
}
add_filter('user_row_actions', 'kv_admin_deactivate_link', 10, 2);
which actually helps to hide the delete link from the users table. but if i go with direct GET link its allowing me to delete.
So is there any function or feature, which will prevent the deletion. | A quick (and dirty) solution would be to prevent the final deletion where it happens (function delete_user). You could implement a little plugin or paste the code into your functions.php:
<?php
/*
Plugin Name: Please don't delete me!
Description: Prevent accidental user deletion of my account
*/
define('PDDM_USER_ID', 1); // User ID of your Account
add_action('delete_user', function($id) {
if ($id == PDDM_USER_ID) {
die('please don\'t delete me!');
}
});
This just stops the script execution just before your user get's deleted.
Not fancy and pretty ... but it works ;-)
br from Salzburg! | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 3,
"tags": "users"
} |
Static page does not show my posts
I have a home.php and an index.php.
Wanting my home.php (set as static) to display 3 grid style showing 3 posts.
This is my current code.
<?php
// The Query
$the_query = new WP_Query( 'cat=4');
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_post();
echo'<li>' . get_the_title() . '</li>';
}
echo '</ul>';
} else {
// no post found
}
*/ Restore original post data */
wp_rest_postdata();
` | So this is the code I have on one of my Website inside the footer, this basically get's the 3 latest posts and displays `the_title` you can change this to show `the_excerpt`.
<?php // news posts loop begins here
$newsPosts = new WP_Query('page=blog&posts_per_page=3');
if ($newsPosts->have_posts()) :
while ($newsPosts->have_posts()) : $newsPosts->the_post(); ?>
<!-- Blogs -->
<div class="post-item">
<!-- This is where you can insert the excerpt -->
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
</div>
<!-- ./Blogs -->
<?php endwhile;
else :
// fallback no content message here
endif;
wp_reset_postdata();
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, theme development, homepage"
} |
Disable delete user
My site has custom post type 'Portfolio'. If a user has at least one Portfolio, how can I disable the option to delete that user?
I found the action/hook `delete_user`, but it doesn't seem right for this issue. | When you click on "delete", the action 'delete_user' will be launched: <
After that you can check, if the user has written at least one 'portfolio' post.
add_action('delete_user', 'sw_portfolio_check');
function sw_portfolio_check( $user_id ) {
$result = new WP_Query(
array(
'author'=>$user_id,
'post_type'=>'portfolio',
'posts_per_page'=>1,
)
);
if ( count($result->posts) !== 0 ){
wp_die("User has a portfolio and can't be deleted");
}
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 5,
"tags": "users, hooks"
} |
Using Easy Google Fonts correctly and Droid Sans on Max OS X
I have Easy Google Fonts working along with my API key entered. However, it doesn't seem to be working.
There is no fallback in my font list and I following settings the font to display in Customise-Typography
font-family: 'Droid Sans';
Here is what I have it set to:
<
Also when my menu was set to Bold for Droid Sans, Mac OS X would not display it properly? | Inside your CSS put the `font-family` inside your `body { }` tag and then it should work.
body {
font-family: 'Droid Sans', serif;
}
Also I recommend setting a fallback font for the reason listed in W3C Schools CSS Web Safe Fonts
Best of luck :) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -2,
"tags": "css"
} |
How to control on which pages the Aldehyde theme's main slider is shown?
The Aldehyde theme is a nice open source theme that comes with a main slider that can be configured in the template's settings. By default, it is shown on the blog page, whether that is the homepage or a static page set via the WordPress "reading settings".
I want to show it instead on multiple other, specific pages. How to? | This cannot be configured in the theme settings. You will need a bit of coding:
1. In your WordPress backend, with the Aldehyde theme set as the active one, navigate to "Design → Editor".
2. In the "Templates" column on the right, select `slider-nivo.php`.
3. You will find that the first non-comment line looks like this:
if ( … && is_blog() ) :
Change the condition to meet your needs. You can use the is_page() function to make the slider show on pages with the given page slugs / IDs:
if ( … && is_page(array('page1', 'page2', 21, 23)) ) :
4. Of course for a clean solution, put this change into a child theme. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "theme development"
} |
For some reason my posts are not showing up on my front page
For some reason my posts are not showing up on my front page after some small changes. Any suggestions? < | I'm assuming we're viewing a "Page" titled "Home"?
Be sure that Settings > Reading has "Front page displays" set to either "Your latest posts" or the correct page has been selected in the option "Posts page". | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -3,
"tags": "pages, homepage"
} |
How to remove #more... from the post "More" link?
When you insert the "More" link into a post using the "Insert More Break" toolbar icon, the url that is generated is appended with "#more-". Thus when you click that link, you get the full post (via single.php), but the browser then scrolls to where the 'more' was inserted.
Is there a filter I can use to remove the "#more-"?
What I want is to _not_ scroll to the 'more' link when the full post is displayed. Thanks. | There you go this will prevent scroll (add to functions.php)
function remove_more_link_scroll( $link ) {
$link = preg_replace( '|#more-[0-9]+|', '', $link );
return $link;
}
add_filter( 'the_content_more_link', 'remove_more_link_scroll' );
Explained in depth Here. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "read more"
} |
Need help with theme Business (Modern Themes): sidebar issue
I'm using Business theme from Modern Themes (modernthemes.net/wordpress-themes/business/).
I have a "problem" that doesn't seem like a real problem because it is shown in the demo of the theme, so it was built to look like that, but it really bothers me.
Author, category, tag and archive page shows a full width posts and a sidebar below posts.
How it looks like (tags page): : ;`
`pathinfo(__FILE__, PATHINFO_FILENAME);`
`SCRIPT_FILENAME`
If no luck still, check `index.php` and then check mu-plugins folder for files. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "debug"
} |
What are available arguments for wp_oembed_get?
I used wp_oembed_get function to embed a YouTube video. It worked like it should.
Now I want to add a class to an embedded element. Is there an argument for this?
Can't find list of arguments for this function anywhere. I tried 'class' but it didn't work. | The whole idea of embedding is that you do not have control over how the embedded content is being styled and it is controlled by the server from which the content is embedded. The embedding server might allow some control over the embedded content via the URL parameters but to know how to achieve that you will have to consult the documentation of the provider.
You can enclose the embedded content in a div with whatever class you want, but that unlikely to help you much. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "oembed"
} |
How woo-commerce store Product Data value in DB?
I am working on a project in which Products are being added by parsing a XML file.
For Variant product I am able to save all attributes and the product variant related to a product , but I am unable to save "Product Data" drop down value as "Variable Prouduct" using parser ( PHP code ).
Is there any metakey /metavalue for this.
Please help me. Thanks | Here is the answer which I have got
// Setting this as a Variable product
wp_set_object_terms( $post_id, 'variable', 'product_type' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, woocommerce offtopic, parse"
} |
Unkown meta_value in ACF
I'm using ACF, but I wonder the meta_value means?
Below is a snippet from my database:
meta_id post_id meta_key meta_value
9394 4661 _carousel_0_image field_5683f27fd880e
So what exactly is `field_5683f27fd880e`? Is the `5683f27fd880e` an serialized or hashed value or something? | For every meta value saved there is a second row prefixed with `_` that stores what field definition this value refers to. Do not delete it.
Your example additionally is a repeater which makes it more complex but the docs has a nice explanation:
> $ParentName_$RowNumber_$ChildName
So you have a repeater field called `carousel` which has a subfield called `image` and this is the first row:
carousel_0_image
As said an additional row called `_carousel_0_image` is saved by ACF to know which field this relates to. It is (if I remember correctly) some index relating to a Custom Post Type that stores ACFs Field definitions.
As a closing note: ACF has support and third party questions usually get closed here as off-topic, I am just responding because I knew this off the top of my head. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "database, advanced custom fields"
} |
wp_enqueue_scripts not working in custom theme
This one may have been answered before but I could not find it anywhere.
I have created a custom theme and a plugin for my site. My theme's `functions.php` file only contain a `wp_nav_menu()` function for generating a menu.
Now in my plugin when I try to connect my CSS and JS with
function my_css_js() {
wp_enqueue_style( 'css_style', theme_URL . 'css/style.css' );
wp_enqueue_script( 'my-jquery_file', theme_URL . 'js/jquery.uploadfile.min.js', array(), null );
}
add_action('wp_enqueue_scripts', 'my_css_js');
This does not load any CSS or JS in on my site.
As you can see I have used `wp_enqueue_style` and `wp_enqueue_script`.
This is not loading the CSS and JS I need.
Is there anything I missed? When I use this same plugin with the same hook in ready made theme this works like charm.
I appreciate any help, thank you | I have found this small error in my code which stops `wp_enqueue_scripts()` to work in my theme was I forget to put `wp_head` in my head section.
For another person who may make same mistake are advised to check that they have include `wp_head` in head part and `wp_foot` at end of your theme. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 6,
"tags": "plugins, theme development"
} |
Why would image paths in wordpress suddenly change?
I'm using the Everglades WP theme, and have had no issues until suddenly I found all the images have different paths in the browser.
Where they are: <
Instead they look like this: <
I'm not sure where the i2.wp.com (sometimes shows up as i0.wp.com) is coming from, or why the path would change in the first place. I've tried disabling plugins, and re-saving permalinks, but to no avail. All the images show up with the correct paths in the Media folder, but not online. I can't for the life of me figure out what might have happened, and have never seen this before.
Any ideas are welcome, thanks. | It looks like you use the Jetpack Plugin with Photon function (Wordpress.com photo CDN)
< <
You have to deactivate the Photon option in the Jetpack plugin settings. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "images, urls, media library"
} |
Pass current post title to a predefined link
I have custom link option which I show on all posts using:
`<?php echo get_option('_custom_link'); ?>`
and let's say, I have defined it with a URL value of ` where `title_of_current_post` is replaced with the corresponding title of the post where the link was clicked.
Is it possible to do something like a placeholder tag e.g. `?ref=%%title%%`?
I'm still trying out a few things, just wanted to know if someone else had done something similar and share their solution. | Looks like it's possible to use a placeholder tag, the following is the PHP code using a `_custom_link` value of `
<?php
// must be within the Loop
$ref_slug = strtoupper(sanitize_title_with_dashes(get_the_title()));
$regex = '(\%\%title\%\%)';
$ref_link = ( get_option('_custom_link') ) ? preg_replace( $regex, $ref_slug, get_option('_custom_link')) : null;
echo $ref_link;
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom field, options"
} |
Variable Products Being Added to Cart with AJAX on Shop and Category Pages
By default, Woocommerce ajax add to cart functionality is only supposed to apply to simple products on archive, shop, category pages, etc.. But for some reason it is also adding variable products to the cart when I click "Select Options." Select Options is supposed to go to the product page. How can I disable ajax add to cart on variable products?
 && $product->is_in_stock() ? 'add_to_cart_button ajax_add_to_cart' : '',`
to:
`$product->is_purchasable() && $product->is_in_stock() && $product->is_type( 'simple' ) ? 'add_to_cart_button ajax_add_to_cart' : '',` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "ajax, woocommerce offtopic"
} |
Add the title attribute to links
I want to add a title attribute to my link like this:
<a href="#" title="here is the title">LINK</a>
I know how to do this in html but I can't expect this from my users.
I can't find anywhere in WordPress how to do this and there isn't a `theme_support` function for this.
I can't be the first to encounter this problem (I hope). | Turns out you are not the only one: <
It looks like this was removed in a recent update (4.2) and I can see why they did it. User interface can be confusing at times.
You can read more about the removal here: <
There is a WordPress plugin, however, that seems to add it back for you. I have not tested, but it should work: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "links, html, title, customization"
} |
How remove the white space between my menu and slider?
This is my site <
When I scroll down, a white space appears between my menu bar and slider.
how do I remove that?
This is what I have done to place the logo at the very top. After doing this, the white space started appearing.
.edgtf-page-header {
margin-top: 30px;
padding-top:290px;
background-image: url('
background-repeat: no-repeat;
background-position: center top;
position: relative;
display: block;
} | Maybe if you take a look at class="carousel-inner skrollable skrollable-between" and use some js to do it as position:absolute and top:0px | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css"
} |
Gravity Forms closes my popup on Validation Error
I am having an issue with Gravity Forms. A user on my site can open a contact form in a popup menu by clicking a 'contact' button. The form is just in an absolute div that I show/hide on the contact button. If a user does not fill out a required field, obviously the form does not validate and does not send. My issue is that if the form does not validate, the popup closes and the user has no idea that their form did not go through. They would have to reopen the popup to see the default gravity forms message saying "this field is required", how can I stop Gravity Forms 'submit' from closing the popup if the form does not validate? | You'll want to make sure you're loading the form with AJAX enabled. I'm assuming that the the form is actually refreshing the entire page (hence the popup closing). If you enable AJAX, only the form should be refreshed and the popup's visibility should not be impacted. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "ajax, javascript, plugin gravity forms"
} |
Use another theme template in my theme
I want to use a different theme's portfolio page in my theme. I just want the content (portfolio layout of the other theme) but my own (active theme) header, footer, sidebar, and everything else. Is there a structured approach for this problem? | Create child theme of the main theme you're using. That way you can override just the parts you want. Reference - <
Hope it helps! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, themes, templates, get template part"
} |
htmll lang="de" but admin page in English
I've set up a multisite Wordpress installation, because I want to work with multipul languages. Everything work except the lang attribute. I want the admin panel to be English, but I want to give lang attribute the value of the language of the site it self (for example german). The only way I see to that is to change the admin panel to that language.
The code I'm using:
<html <?php language_attributes(); ?>>
The value I get on the site (with English admin panel):
<html lang="en_GB">
The value I want to get with the English admin panel:
<html lang="de">
My site uses a folder for the language not a sub domain. So the German site is: < | This is fixed. I made a small script to get this working.
Because it was a multi language site I just named the site's to the language they should be in. So the English page is named English, German page is called German etc. Made a small php script to check what the page name is so a variable will fill this one in.
PHP code:
# Check language of page
$currentLang = get_bloginfo();
if ($currentLang == 'English') {
$htmlLang = "en-GB";
}
elseif ($currentLang == 'German') {
$htmlLang = "de";
}
# etc | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "multisite, html, multi language"
} |
REST API: How can I restrict a custom post type to only be accessible by authenticated users?
I have a `custom post type` configured to be accessible via the WP Rest API v2.
How do I lock the access to this `custom post type` so that only the authenticated users can perform `GET` requests? | Looks like I found a snippet that do exactly that. It's from Daniel Bachhuber, the API developer.
add_filter( 'rest_authentication_errors', function( $result ) {
if ( ! empty( $result ) ) {
return $result;
}
if ( ! is_user_logged_in() ) {
return new WP_Error( 'restx_logged_out', 'Sorry, you must be logged in to make a request.', array( 'status' => 401 ) );
}
return $result;
});
This is posted in his gist on GitHub. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "custom post types, api, capabilities, user access, rest api"
} |
How Yoast SEO plugin works with variable %%name%%?
I know that Yoast SEO plugin doesn't create any database table then why in wp_postmeta numbering of meta_id are not continuous?
Is it because of Yoast Plugin?
Also I want to know how its feature of automatic seo by default %%title%% in post works?
Because when I tried to use variable %%name%% with %%title%% in post type page but %%name%% appears as it is and %%title%% shows title of my page.
. The variable `%%name%%` is NOT getting parsed properly.
However, if you view the page itself, the variables **are** being parsed properly, including the `%%name%%` variable. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "database, plugin wp seo yoast"
} |
WordPress Post Visibility Options for Frontend
I want to have a code/clue to add "wp post visibility" option for front-end. I will use radio buttons get a value from user. e.g. if user selects "No" the post will become private else if user chooses "Yes" it will be public. | One option is to use Ajax. I wrote this tutorial on how to use Ajax with WordPress and if you follow those steps, you'll get the general idea. Of course, you'll have to write some HTML to display the radio buttons, and then in your Ajax Callback function, you'll want to change the post status to private or publish depending on the user's response. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, post meta"
} |
Custom Shortcode, functions PHP WP_Query loop
I have the following code in my functions.php file:-
function featured_properties_func( $atts ) {
$args = array(
'posts_per_page'=> -1,
'post_type' => 'properties',
);
$featured_query = new WP_Query( $args );
if( $featured_query->have_posts() ):
while( $featured_query->have_posts() ) : $featured_query->the_post();
$featured_properties = get_the_title();
return $featured_properties;
endwhile;
endif; wp_reset_query();
}
add_shortcode( 'featured_properties', 'featured_properties_func' );
When I output the shortcode I'm only getting one value where as it should be returning 6.
What I want to do is loop all the properties and return the title of each, any ideas what I am doing wrong? | You are returning inside your loop - so it returns on the first iteration, giving you one result only.
You should build a string inside your loop instead, and only return when the loop is over.
Something like
$featured_properties = '';
if( $featured_query->have_posts() ):
while( $featured_query->have_posts() ) : $featured_query->the_post();
$featured_properties .= get_the_title() . '<br />';
endwhile;
endif; wp_reset_query();
return $featured_properties; | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "functions, loop, shortcode"
} |
Twentyfifteen style author comment
I am using twentyfifteen and I have made a child theme. I am trying to style author comments differently than visitor comment.
In other words I want the author replies to have a black background.
After searching the web for hours I give up and came here. Most of the tutorials I have found are for older themes which is written differently from twentyfifteen.
Please help me out if you can. Any suggestions will be appreciated! | These are CSS classes for styling...
comment-author-admin bypostauthor
For (your) example:
.commentlist .byuser {background-color: black;}
.commentlist li ul.children li.byuser {border-top: 10px solid #e18728;} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, css"
} |
Struggling with array and foreach loop
I have a function that outputs an array with 2 objects(?):
`Array ( [de] => 166 [it] => 167 )`
Where [xx] is de language code and the number is the pageID.
I'm having a meltdown in my brain as I cannot figure out anymore how to use the pageID's in a foreach loop.
EDIT: See here as the reference of what I'm doing.
The filter outputs the above and I only need to two numbers (which are page-ids), but I cannot figure out how to get them out.
Can someone lend me a helping hand to show me how to do this again. I know it should be something relatively simple, but I'm drawing blanks :(
Thanks in advance! | You can get an array with just the numbers by using
array_values($your_array);
It will return an array with just the numbers. Is this what you need, or a string with a comma separated list of IDs?
If that's the case, use this:
implode(",",array_values($your_array));
Hope this helps. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "array, php"
} |
Redirect to another page if the user is logged in when pressing again the login button on menu bar
So I have this button on the menu : "My account" that lets the user login on the website and as soon they log in they're redirect to their dashboard.
What I'm trying to achieve is if he's logged in and presses again the "My account" button to be redirect to the dashboard, because right now is redirecting to there account settings.
add_action( 'template_redirect', 'dashboard_redirect' );
function dashboard_redirect()
{
if( is_page( home_url( '/min-konto/' ) ) && ! is_user_logged_in() )
{
wp_redirect( home_url( '/dashboard/' ) );
exit();
}
}
I'm kinda new to WP. | Firest of all you have to make sure that is_page() is right. I think the right syntax is
is_page( 'min-konto' )
or
is_page($pageid)
then the function should be
if( is_page( $account_settings_page_id ) && is_user_logged_in() ) {
wp_redirect( home_url( '/dashboard/' ) );
exit();
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "functions, redirect, actions"
} |
How do I change the woocommerce product gallery to show all thumbnails instead of three at a time in a carousel?
I am building a site for a client and I can't seem to figure out how to remove the product gallery carousel setting. For the final result, I want to be able to see all the thumbnails at once and not have to use the nav arrows to cycle through. It could be displayed in a grid style setting with 3 images per row or something (preferrably) like this: < I also would like to show a caption below or above each thumbnail.
Any suggestions?
What I'm working on: < | Go to woocommerce folder-> template single product -> product-thumbnail.php from that you need to delete the slider class | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic, gallery, thumbnails, captions"
} |
Plugins rewrite rules the right way
I need to create rewrite rules for my plugin. This plugin will be running on a very large WordPress Network (+2000 sites) so performance is important.
Most tutorials and the codex recommend to `flush_rewrite_rule` on plugin activation and then to `add_rewrite_rule()` on `init`. But since rewrite rules are stored in DB it seems to me that we are wasting resources running `add_rewrite_rule` on every `init` (=every page load).
On the other hand you can't only rely on the plugin activation hook because if another plugin flush the rules then your rewrite rules would be lost.
I know that `add_rewrite_rule` is just some simple string and array manipulation and is not SUPER expensive in term of resources but it still feel not right....
Am I missing something? | The add_rewrite_rule function doesn't change the database. Just an array in memory. It is not an expensive operation.
The alternative is to add code to detect whether your rule is there, which is actually more expensive than just modifying the array. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "hooks, performance, rewrite rules, init"
} |
Where to find WP_Query class?
I cannot find WP_Query() in my wordpress folder, the global refers to $wp_query but I don't find the class itself. From my wordpress folder, or here directly : < | Look in the query.php file. The class is there. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query"
} |
My Menu Disappears on my Custom Link Homepage on Mobile
My menu on my custom link homepage disappears on mobile, or when the window is small on web browsing.
The thing is on all my other pages on mobile, the menu is there in the form of three lines - as a drop down menu. It is on every other page, except for my static custom link homepage.
Any ideas?
I saw the similar question and answer on this website, in relation to going into menu and setting it as primary menu - mine is set as primary menu and did not resolve the issue.
website: www.racheldhanjal.com
Rachel | The mobile nav menu in your theme appears to be injected via JavaScript. On pages other than the home page the mobile nav does appear. It looks like the home page is the only page throwing JS errors; they appear to be associated with Mailchimp and/or Contact form 7 . Try disabling plugins for both Mailchimp and CF7. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "menus"
} |
Different single page templates for taxonomies
In my WordPress theme I created the custom post type `articles`. I also created two taxonomies called `article` & `news`. How can I display each taxonomy in its own single template? For now it only displays using the `single-articles.php` template. | Use the single_template filter in your functions file with the correct conditional tag
add_filter( 'single_template', 'single_tax_term_template' );
function single_tax_term_template( $single_template ) {
global $post;
if ( has_term( '', 'article' ) ) {
$single_template = dirname( __FILE__ ) . '/article.php';
}
if ( has_term( '', 'news' ) ) {
$single_template = dirname( __FILE__ ) . '/news.php';
}
return $single_template;
}
This code targets all terms in news and article taxonomies. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom taxonomy, templates"
} |
How can we disable a custom post type archive page but enable its feed?
To disable a custom post types archive page, we should use the following code:
$args = array(
'has_archive' => false,
);
But when we use `false` for `has_archive`, the feeds page (like : `name.com/books/feed`) of that custom post type becomes disabled too. Now I want to know how I can disable custom post types archive page but keep the feed active? | Finally I found a solution for it. I set `has_archive` to `true`. Now both the feed and the archive page of CPT are active. To only disable the archive page of CPT, I use the following filter in the `functions.php` file:
function AryanThemes_disable_cpt_archive_template(){
if ( is_post_type_archive('cpt') ) {
global $wp_query;
$wp_query->set_404();
status_header( 404 );
get_template_part( 404 ); exit();
}
}
add_filter( 'archive_template', 'AryanThemes_disable_cpt_archive_template', -1 ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "custom post types, feed"
} |
Sort Popular Posts by Views for the Last Week
I'm trying to sort the popular posts so it shows the most visited in the last week, but it hasn't worked. Anyone have an idea of why it isn't working?
<?php
$popularpost = new WP_Query( array (
'posts_per_page' => 5,
'ignore_sticky_posts' => 1,
'meta_key' => 'sw_post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'date_query' => array (
array (
'year' => date( 'Y' ),
'week' => date( 'W' ),
),
),
) );
while( $popularpost->have_posts() ) :
$popularpost->the_post(); ?> | Use `strtotime` to compare dates.
$start = strtotime('yesterday');
$end = strtotime( '+1 week',$start);
$args = array(
'posts_per_page' => 5,
'ignore_sticky_posts' => 1,
'meta_key' => 'sw_post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'date_query' => array(
'after' => $end,
'before' => $start,
),
);
$popularpost = new WP_Query( $args );
if ( $popularpost->have_posts() ) {
while ( $popularpost->have_posts() ) {
$popularpost->the_post();
// Do your stuffs
}
}
Please note, this will return the posts from last 7 days, not last week. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "loop, meta query, popular posts"
} |
Articles are text-only in any "Category" instead of HTML
I run a Wordpress blog at < and a lot of articles are using HTML codes (mainly `<h*>`, `<p>`, `<a>` and `<figure>`). Those tags are correctly displayed on the homepage and inside any blog post.
But when you browse a category (as < ), then the articles are texts only. Same when you're doing some research on the blog.
I'm okay having text-only version when doing a research (since WP displays the part of the article where the words were found), but how can I have the HTML version of the articles on the categories? Or is it a plugin that have broken that feature (aka, if WP actually shows HTML in categories, then my theme or plugins have broken it)? | **The theme uses`the_excerpt()` instead of `the_content()`**.
I had created a child theme before (so I don't modify the source theme directly: only the child one), so I only had to copy/paste the PHP file (`archive.php`) from source theme to child theme, and change `the_excerpt()` for `the_content( __( 'Read more ›', 'my-domain' ) );` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "posts, categories, html"
} |
Comment form not showing up without comments
My posts dont show the comment form unless that post already has comments. If post has one or more comments, everything works perfectly.
Everything used to work fine (that's why some posts have comments) and I have no idea why this is happening as I haven't touched any settings.
According to my settings, comments are enabled without restrictions and they are not closed after specific time. I also doubt that there's anything wrong with the code since putting `<?php comment_form(); ?>` on my template bahaves the same: doesn't show up without comments, shows up with comments.
I also tried to deactive all plugins one by one to see if some plugin was causing problems, but without results.
Does someone know what could be causing this issue? | Ok I feel stupid now. The problem was that for whatever reason some of the posts had comments disabled. I did not know that the only place where they could be toggled was under "Quick Edit". Problem solved... | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "comments, comment form"
} |
How do I remove the date and category form my portfolio pages
This is one of my portfolio page
Whenever I wanted to remove dates and category from blog posts I always used this code
function jl_remove_post_dates() {
add_filter('the_date', '__return_false');
add_filter('the_time', '__return_false');
add_filter('the_modified_date', '__return_false');
add_filter('the_category', '__return_false');
add_filter('get_the_date', '__return_false');
add_filter('get_the_time', '__return_false');
add_filter('get_the_modified_date', '__return_false');
add_filter('get_the_category', '__return_false');
}
add_action('loop_start', 'jl_remove_post_dates');
Since, in this case they are portfolio, I replaced posts with portfolio. But no luck. | As already mentioned in my comment above, there was not much information to work with.
Assuming that a quick workaround using `CSS code` to overrule settings is enough,
here a snippet which will hide the output as asked.
_Be aware that this will hide those`CSS classes` for the whole site._
Add the snippet below at the end of your `style.css` in the folder `wp-content/themes/your-theme-name`.
_Please make always a copy/backup when starting to add/edit files when using`code snippets`._
.edgtf-portfolio-single-holder .edgtf-portfolio-info-item {display:none;}
> Note: I use Firefox -Developer Edition to find specific `CSS properties`.
> Ofcourse you can use other browsers also, use the right mouse button and select `Inspect Element`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "functions, javascript"
} |
Malformed RSS feed
I am trying to connect my site's RSS feed to Mailchimp, but my feed doesn't pass basic RSS validation (<
The reason for that is 3 empty lines at the beginning of the feed, which I am clueless as to where they came from.
I tried disabling all plugins but the result is the same. Assuming the culprit is my theme - where should I go search for it? My theme has no feed*.php files in it. | Found the culprit.
functions.php had a few extra blank lines after the closing ?>
Once removed - it worked well | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, feed"
} |
What to do when child theme is out of date with parent theme
I inherited a site with Genesis as the parent theme and a Genesis child theme. The parent theme has smoothly been upgraded over the years.
The child theme, however, was based on an older version of Genesis. So it seems like there is an incompatibility between the child theme talking to the parent. e.g. the responsive style does not exists. I've run vimdiff between the child-theme/style.css and genesis/style.css and That's why I think they are not fully compatible.
So I guess my question is what should my next steps be? I cannot differentiate between the core child theme styles and the custom styles written by the site maintainer before me.
* The Wordpress UI tells me Genesis is at version 2.2.5
* The genesis/style.css file tells me it's version 2.1.2
* And my child theme says `Template: genesis` `Template Version: 1.7.1` | So honestly, I think this is just my fault. I was under the impression that a child theme extended the parent similar to how it works in drupal. It seems like the parent theme here has little to do with the display and more about framework type stuff, seo. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "theme development, child theme, genesis theme framework"
} |
Why doesn't the "Press This" bookmarklet work on GitHub?
This is a mystery to me. The "Press This" bookmarklet works well for me, everywhere except when I try to press one of my GitHub repositories.
It doesn't just fail to grab anything, the window fails to open altogether.
Does anyone else experience this? Is this a known / documented bug? Is there an explanation? | This is due to the Content Security Policy (CSP) that Github rolled out in April 2013. CSP _shouldn't_ cause problems with bookmarklets, but it does in practice.
The issue isn't specific to PressThis either. It causes problems with bookmarklets from Pinboard, Pocket and Instapaper.
In Chrome you can hit `F12` to open the developer tools and see the error:
 for posting in social networks I need to have an extra permalink like mydomain.com/?p=123 (or something like that but with my exact domain).
P.S: I searched and came across yourls.org which is great but I'm not sure if I can have in the same directory as Wordpress!? | You can always use the post ID to link to a page, like this:
You can find out the Post ID right from the post overview screen. If you hover over the "Edit" or "Delete" link, you can see that the URL has a parameter `post=`. The number behind that is your page ID.
It could happen, that WordPress redirects your "post ID permalink" to the "real" version with the slug, but you are good to use the numeric one for linking. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "permalinks"
} |
How would you detect if WordPress is installed in a subdirectory (not root)?
I want to check if a WordPress installation is working from a subdirectory.
Common methods to achieve this are listed here: <
these usually involve changing an index file and requiring WordPress main file from there, perhaps changing rules in htaccess if using Apache - there's no setting up constants from what I can see
so, how would you detect reliably if WordPress is not running from a directory root? | You need to check if the siteurl differs from the home URL:
if ( get_option( 'siteurl' ) !== get_option( 'home' ) ) { // whatever
This also works if `home` is a subdirectory of the root, with WordPress installed in yet another subdirectory. For example: domain.com/blog (URL) and domain.com/blog/wordpress (siteurl). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "directory, installation, subdomains, domain"
} |
Can't delete the two native plugins of Wordpress
Just installed WP in Ubuntu 15.10 desktop on my local, home PC. It's the first time I install this CMS in Linux.
After install I came to delete the two native plugins, Aksimet & Hello Dolly.
In the first time I did so I was (strangely) asked to fill in FTP credentials. Since I have no FTP I ran the FTP problem in Google and after some reading added `define('FS_METHOD', 'direct');` in the end of wp-config.php ... It solved this prob, but then came another - an error this time, occuring when I try to remove these two plugins:
> Plugin could not be deleted due to an error: Could not fully remove the plugin(s) akismet/akismet.php, hello.php.
did `sudo chown benwork -R .` and also `sudo chgrp www-data -R .`
Nothing seems to help. Will thank you for your help, | You need to make sure that the folder permissions/ownership are correct. Run this command to set ownership:
chown -R apache:apache /var/www/wordpress/ | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, linux"
} |
Gallery Shortcode Showing IDs
I'm trying to include a gallery in my custom post type. The image gallery works in the editor, but when I view the post I get this.
[gallery link="file" ids="590,589,588,587,586,585,578,580,581,582,583,584"]
My content looks like this:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
$content = get_the_content();
/** ... **/
?>
<p><?php echo $content ; ?></p>
;
and replace:
<p><?php echo $content; ?></p>
with:
<?php the_content(); ?>
See this note on the Codex page for `get_the_content()`:
> An important difference from the_content() is that get_the_content() does not pass the content through the 'the_content' filters. This means that get_the_content() will not auto-embed videos or expand shortcodes, among other things. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "gallery"
} |
Query wp_postmeta into an array based on post_id
I know this might be a simple question but can someone explain to me how to query the WP database and pull in all the "meta_key" and "meta_value" from "post_id" into an array? I have looked at code and tutorials but I still cant figure out how to make it work correctly. | You can use `get_post_meta( $post_id )` to retrieve all of the meta for a post. It will give you more than you need but you can filter it out after.
Here is the code reference - < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, database"
} |
enqueue_parent_style
I am trying to change my @import style.css to wp_enqueue_style for my child themes. I added the following into my functions.php child theme and it returns a 500 error. I looked at this and pretty much followed it to the T. I also looked at this but the answer didn't make sense to me. I am pretty new at this so I just couldn't make the jump.
function child_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri () .'/style.css' );
}
add_action( 'wp_enqueue_scripts', 'child_styles' );
Any help would be good here as I would rather enqueue scripts the faster and better way. I am testing this on my local before activating it live, so I can't give the site URL. | I think if you change your `wp_enqueue_style` to the one below it will work perfectly. This is the way I do it inside my own `functions.php` file.
function wpse_scripts() {
// Theme Stylesheet
wp_enqueue_style('style', get_stylesheet_uri());
}
add_action('wp_enqueue_scripts', 'wpse_scripts');
Although you can do it the way your doing it, it's just you've added a `/` before your `style.css` and you don't need that. By adding the `/` your script is looking for a folder called `style.css`
function wpse_scripts() {
// Theme Stylesheet
wp_enqueue_style('style', get_stylesheet_directory_uri() . 'style.css');
}
add_action('wp_enqueue_scripts', 'wpse_scripts');
The way your doing it would be done like this
Here are some places to start when changing your `functions.php` in your child theme.
**Child Theme** | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp enqueue style"
} |
Buddypress Member list not showing admin and mods
I'm trying to get a list of members for a buddy press group but the result leaves out members that are admins or mods even though exclude_admins_mods=false has been specified as a parameter. This is what my code is
global $bp;
$id = 1;
if (bp_group_has_members('group_id='.$id.'&exclude_admins_mods=false')) :
while ( bp_group_members() ) : bp_group_the_member();
bp_group_member_link();
echo '<br>';
endwhile;
else: ?>
<div id="message" class="info">
<p>no members.</p>
</div>
<?php endif; ?>
Have I missed anything obvious here? | You don't need this `global $bp;`
Try passing an array:
$id = 1;
$args = array( 'group_id' => $id, 'exclude_admins_mods' => false);
if ( bp_group_has_members( $args ) ) : | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development, buddypress"
} |
Check if page parent has certain template
I want to check if a page has a parent with a certain page template attached to it.
If I know that I can determine which scripts to load or not.
Normally I would just get the page template and if it is a match load the scripts needed but now I have the script in my `functions.php` file and can't get the `$page->ID` to check.
I don't really know how to solve this. In my `functions.php`:
require_once('js/my_script.php');
`my_script.php`:
add_filter( 'admin_post_thumbnail_html', 'function_name');
function functions_name( $myhtml ) {
//do stuff
};
This hooks into an existing function. I can't check within the function because that would disable the complete function if the statement would be false. | This question has been answered on Stack Overflow before: <
add_action( 'admin_head', 'check_page_template' );
function check_page_template() {
global $post;
if ( 'page-homepage.php' == get_post_meta( $post->ID, '_wp_page_template', true ) ) {
// The current page has the foobar template assigned
// do something
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "php, functions, filters, hooks"
} |
Last modified field for user profile?
Is there a plugin or a known way to track user profile changes and save a last modified date in Wordpress?
I tried with ACF, but it doesn't have an option to auto update this field.
Thanks in advance. | As mentioned in the comments, you can use the Plugin and Metadata APIs to attach some functionality to the `'profile_update'` action such that whenever a user's profile information receives an update, custom user-metadata is set to the time of the update:
function wpse216609_update_profile_modified( $user_id ) {
update_user_meta( $user_id, 'wpse216609_profile_updated', current_time( 'mysql' ) );
}
add_action( 'profile_update', 'wpse216609_update_profile_modified' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugins, custom field, advanced custom fields"
} |
How to display alt tags in img src?
I'm working off a custom theme which they entirely left out including the alt tag in the img source.
Here is an example of the code:
<img src="<?php echo get_field('image')['sizes']['large']; ?>">
I was searching to find the answer and found this to add, but does not work:
<img src="<?php echo get_field('image')['sizes']['large']; ?>" alt="<?php the_title_attribute(); ?>>">
I'm still pretty much a novice with Wordpress templates. Is there something I'm missing. | You are using the Advanced custom fields plugin. The documentation for images: <
To display the alt-tag for example, you can use this snippet:
$image = get_field('image');
if( !empty( $image ) ) {
$alt = $image['alt'];
...
echo '<img src="..." alt=" . $alt .">'
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "images, title"
} |
Determine when a custom field was last updated?
Would anyone know of a way to determine when a custom field for a post was last updated?
I'm trying to write something that says "If CUSTOMFIELD was updated in the last 24 hours don't do anything, else update it" but don't see any time stamps in the database for this.
Any clever ideas floating around? | I would add another custom field that stores the update time.
Then create an `add_action` function for update_post_meta to also save the timestamp at the same time you write to CUSTOMFIELD.
The action triggered when adding a custom field is `add_post_meta` and when updating a custom field `update_post_meta` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom field"
} |
Error while downloading WordPress themes
Installing Theme: Luminescence Lite 1.3.0 Downloading install package from <
Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-wp-http-curl.php on line 324
This is the error I am getting when downloading any WordPress themes. Please tell me how to resolve this problem.
Thanks. | This might be a problem with slow connection which causes PHP to time out, you can try again later.
The alternative is to download the theme zip file to your computer and upload it from there into the site. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes"
} |
How to handle "the_terms" inside loop
I have been searching google but I am really confused. I am trying to display the terms of the taxonomy assigned to the post. I am using `the_terms($post->ID, 'locations');`. The custom taxonomy is hierarchical.
Example: 3 terms assigned to post: `USA(parent) > FL(direct child of "USA") > Miami(direct child of "FL")`. What I get: `FL, Miami, USA` which means the terms are being displayed in alphabetical order. I want them to be displayed like: `Miami, FL, USA`. Can this be achieved? I would also like to remove the anchors from the terms and `strip_tags(the_terms($post->ID, 'locations'))` doesn't seem to work.
While searching google some people use `get_terms()` some other `get_the_terms` and others `the_terms` which is what I use and seems to work - output the terms. What is the difference between those functions? Am I using the right one? | To answer your first question
> What is the difference between those functions
* `get_terms()` returns an array of terms objects that belongs to a specific taxonomy
* `get_the_terms()` returns an array of terms belonging to a post
* `the_terms()` displays an HTML formatting string of term names belonging to a post
Because you need your terms not hyperlinked and ordered according to parent, I believe `wp_get_object_terms()` will be a better option here. `wp_get_object_terms()` also returns an array of terms belonging to a post, but is more flexible. You do pay for this flexibility though as you make an extra db call per post.
With this all in mind, you can try the following: ( _All code is untested_ )
$args = [
'orderby' => 'parent',
'order' => 'DESC'
];
$terms = wp_get_object_terms( $post->ID, 'locations', $args );
$names = wp_list_pluck( $terms, 'name' );
$output = implode( ', ', $names );
echo $output; | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "custom taxonomy, loop, terms"
} |
To use custom post types, or not to use
I have in the past few years done more and more development in Wordpress and would like to get some feedback about custom post types/taxonomies.
What are the pros/cons of using custom post types, rather than creating your own database tables and your own admin pages? I have myself always used posts/taxonomies, but found myself restricted by the pre-defined relationships between each. I also noticed some modules do use them, some don't.
What would you guys suggest, and if both could apply, what's the logic behind it? | The rule of thumb in wordpress development is that you should stick with the highest level API you can use. From software development perspective it helps you get a better documentation for your code and reduce the maintenance cost due to the backward compatibility policy.
As CPTs have wrapper APIs in core and costume tables do not, it is easy to see that by default you should prefer CPT, and there should be very very very strong reason to use additional tables.
The only somewhat plausible reason to use additional table is if you need to be able to drop it, or you need a different index structure. Even then not sure if you will gain any actual performance benefit over doing it with less optimized queries.
[joking] If you don't have 20k reputation on this site, additional tables are just not for you [/joking] | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "custom post types, plugins"
} |
Can I verify nonce which was generated on a different WP site?
I have a form with the action going to a different wordpress site. I want to use wp_nonce to generate fields in the form on site A. Can I use wp_verify_nonce on site B to verify the nonce fields? | In theory yes, but it will be a very bad thing to do. For that you will need to have the secret used to generate the nonce at site A in site B which means tht if site B is compromised site A might be as well (there is also some time synchronization that needs to be done between the site, but that the lesser worry).
There are two ways to properly go about it
1. don't use nonce at all. nonce are there to protect registered users and if the submitter of the form is unlikely to be registered or the form do not do anything destructive on the server, then no point in using them
2. Site A should embed the form as an Iframe from site B. That way the nonce was generated by site B and it can verify it without knowing the secrets of site A | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "forms, nonce"
} |
Set Custom Taxonomy to Entire Site Programatically
I want to create and set a custom taxonomy site-wide based on the users location so that I can call `taxonomy_exists( $country )` to determine if a user is located in a specific country.
I've installed the GeoIP plugin that lets me get the user's country code from `$userInfo->country->isoCode`.
To register the custom taxonomy, I have the following function. But what should 'object type' be if I want to apply the taxonomy to the entire site?
add_action( 'init', 'create_country_taxonomy' );
function create_country_taxonomy() {
register_taxonomy(
'country',
$object_type, // Set to what?
array(
'label' => __( 'Country' ),
'rewrite' => array( 'slug' => 'location' ),
)
);
}
Finally, how can I set the user's country taxonomy to `$userInfo->country->isoCode`? | I got it to work by registering a custom taxonomy...
add_action( 'init', 'create_country_tax' );
function create_country_tax() {
$userInfo = geoip_detect2_get_info_from_current_ip();
$country = $userInfo->country->isoCode;
register_taxonomy($country,'country');
}
and then calling `taxonomy_exists('US')`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom taxonomy"
} |
Wordpress custom plugin developement
I'm trying to make a page in my plugin, but don't want it to appear in admin_menu, but just in my plugin page menu! I have a lot of pages, don't want them all to appear as sub menus! any ideas? | Use `add_submenu_page` and set `$parent_slug` to `null`:
add_action('admin_menu', 'wpdocs_register_my_custom_submenu_page');
function wpdocs_register_my_custom_submenu_page() {
add_submenu_page(
null,
'My Custom Submenu Page',
'My Custom Submenu Page',
'manage_options',
'my-custom-submenu-page',
'my_custom_submenu_page_callback',
);
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development"
} |
Append woocommerce category to product title globally?
I am trying to append the product category to the product title in woocommerce, this needs to be on a global level (so it works everywhere).
Ive tried the following code which I thought would work but it doesn't, it appends the category name above the product image on archives only
add_action( 'woocommerce_before_shop_loop_item_title', 'my_add_product_cat', 1);
function my_add_product_cat()
{
global $product;
$product_cats = wp_get_post_terms($product->id, 'product_cat');
$count = count($product_cats);
foreach($product_cats as $key => $cat)
{
echo $cat->name;
if($key < ($count-1))
{
echo ', ';
}
else
{
echo '<br/>';
}
}
} | WooCommerce uses a single hook to display many things and just changing the hook priorities change the order of elements.
Just change the hook and their order to achieve your goal.
add_action( 'woocommerce_single_product_summary', 'my_add_product_cat', 6);
add_action( 'woocommerce_shop_loop_item_title', 'my_add_product_cat', 11);
I have given `woocommerce_single_product_summary` priority to `6` because single product title displayed at same hook with priority of `5`.
The same thing I did for archive products title. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
What is the code for showing Custom Category and Subcategory Page?
hello
We have categories and subcategories like this :
- Category 1
-- SubCategory 1
-- SubCategory 2
-- SubCategory 3
- Category 2
- Category 3
I have one style for all Categories **level 1** and one style for all subcategories **level 2**
I want a code to act like this :
If it was one of Categories level 1 show {
cat1.php (A page that is fix and show some fix content)
}
else if it was one of SubCategories of level 2 show{
cat2.php (A page that show only last articles or posts in this subcategory level 2)
}
end;
thanks for your help | I found 2 ways for my problem :
1- you can create a file with name "category.php" for all of your categories and then for every category that you want to add a diffrent style you should create a file like this>> "category-id.php" OR "category-name.php" .
2- another way is that you can do this work by if and else , you should use this code :
<?php if (in_category('name')) {
echo 'htmlcode';
}
elseif (in_category('name-2')) {
echo 'htmlcode';
}
else {
echo 'htmlcode';
}
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "custom post types"
} |
What happens to my older posts if I switch to a child theme?
I have a theme that has one custom post type. I want to mess with its templates and styles.css file. What happens to my older custom posts in case I switch to using the child theme. Do they vanish? | Nothing would happen, everything would remain the same. Child themes inherit the functionality of the parent theme.
Just a few notes
* All posts regardless of post type is stored in db, so they never "disappear" even when the post type does not exist anymore.
* Custom post types and custom taxonomies **should** be registered in a plugin to keep them available even when you change themes | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, child theme"
} |
Displaying text if post was within 5 hours
Currently I have the following string.
$timeago = human_time_diff( get_the_time('U'), current_time('timestamp') );
print $timeago;
This returns results that looks like this.
1 min, 1 hour, 1 week, 1 month, and 1 year.
I am trying to figure out how I can make this work using an `if` statement to detect if the post has been posted within the past 5 hours, and if it has make it echo " **NEW** " but if not, don't echo anything.
**EDIT:** I tried the following with no success... I am getting confused on how to make it check for the hours portion as well as the number portion I guess.
$timeago = human_time_diff( get_the_time('U'), current_time('timestamp') );
print $timeago;
if( $timeago >= 0 && $timeago <= 5 )
{
print 'NEW';
} | `human_time_difference()` will not work here as it returns a string in a human readable form. However, we can use some of the logic used there to construct a workable function
You can try the following: ( ** _Untested_** )
function get_custom__time_diff()
{
global $post;
// Get the current time
$current_time = time();
// Get the post date
$post_date = get_the_time( 'U', $post );
// Get the amount of seconds in 5 hours
$test_time = 5*HOUR_IN_SECONDS;
$diff = $current_time - $post_date;
if ( $diff < $test_time )
return 'New';
return '';
}
You can then call it as follow inside the loop
echo get_custom__time_diff(); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, functions"
} |
PHP: Showing currency sign if input is a number
I have a field that lets me enter a price for a product in 'edit post'.
Here's how it's currently called:
<span class="price"> "$" <?php echo get_post_meta(get_the_ID(),'si-price',true); ?> </span>
Because some products are discontinued, I would like to only show the "$" if what I type in the box is a number. That way I can have products with no price, and have some products marked as "coming soon" etc. without having the '$' in front of it.
I have tried:
<?php
$price = get_post_meta(get_the_ID(),'si-price',true);
foreach ($price as $element) {
if (is_numeric($element)) {
echo '$' $price;
} else {
echo $price;
}
}
?>
No joy! Any help would be greatly appreciated. | Here you go:
According to documentation of get_post_meta , It will return a single value if the third parameter is true. It should be false to return an array.
<?php
$price = get_post_meta(get_the_ID(),'si-price');
foreach ($price as $element) {
if (is_numeric($element)) {
echo '$' . $element;
} else {
echo $element;
}
}
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php"
} |
Display custom post using ID
In my theme, I have a custom post type called sliders. Here the user is allowed to upload images in a `meta-box`. So, the images are saved as meta data in `wp_post_meta` table.
Now what I want to do is, displaying a slider using its ID.
I did like following but no result
$my_query = new WP_Query('post_type=sliders&p=411');
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
the_post();
endwhile;
}
This doesn't display anything. No even errors. Anyway, If I used `the_title()` instead of `the_post()`, it shows the title of the slider fine. Same for the `the_author()` It shows the author without error.
Why is this weird ? | EDIT: deleted incorrect information
I see what you are missing now. Without knowing the specifics, I tried to point you in the right direction with this:
$my_query = new WP_Query('post_type=sliders&p=411');
if( $my_query->have_posts() ) {
while ( $my_query->have_posts() ) : $my_query->the_post();
// Get the specific meta data for the current post
$saved_slider_meta = get_post_meta( get_the_ID(), 'slider_meta_key' );
// Echo the data
echo $saved_slider_meta;
endwhile;
// Restore original post data if there are other loops
wp_reset_post_data();
}
Here is more information about WP_Query. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, theme development"
} |
Is it possible to prevent users from uploading small images?
Is there a way to prompt an editor whenever they try to upload an image smaller than 350px width? Essentially rejecting any image uploads that are smaller than 350px width?
Thanks | Here you go:
if(!current_user_can('delete_others_posts')){
/*Handling wp media uloads*/
add_filter('wp_handle_upload_prefilter','lets_handle_img_width');
function lets_handle_img_width($file)
{
$img = getimagesize($file['tmp_name']);
$width = $img[0];
if ($width < 350){
$file['error'] = "Image is small too small. Get something of width more than 350px.";
}
return $file;
}
}
Check official documentation about wp_handle_upload_prefilter. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "images, post thumbnails"
} |
Sort users by userID by default on users.php
I want to sort users by User ID on `users.php` by default. The page is currently ordered by `username` as default.
Is there any hook to alter the `order_by` option on `users.php` ? | You can use `pre_get_users` since WP 4.0.0
function my_user_sort( $query_args ){
if( is_admin() && !isset($_GET['orderby']) ) {
$query_args->query_vars['orderby'] = 'ID';
}
return $query_args;
}
add_action( 'pre_get_users', 'my_user_sort' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "users"
} |
Is the login encrypted before it is sent? If so how to do I encrypt it the same way?
I've moved my WordPress site onto a https server, but now I'm wondering if I still need to manually encrypt the login credentials for my remote login.
Is the default login encrypted before it is sent? Everything I've read, code included, is all plain text which is really bad for http sites.
In my other projects we used something like an md5 hash to encrypt the password before sending it. But I don't have that project and I don't know if WP is storing plain text passwords or hashed. So I'd rather use existing WP login code if it's available or an example code of how to encrypt it before sending it would help.
PS I'm logging in via a remote application.
PSS I've also seen the other posts and this is not a duplicate. | wordpress do not encrypt anything at client side, but encryption on client side do not help at all with security, it just make password stronger but do not help at all against Main In The Middle, or eaves dropping attacks. No matter how strong is your password encryption, if you send it over HTTP, once I know it, lets say by monitoring wifi traffic, I can use it myself.
Using HTTPS is the only real solution as the protocol layer ensures that everything is encrypted in a unique way per each connection therefor no one can repeat the same packets and gain access as it will fail in the protocol level.
short answer: with HTTPS you don't need to "encrypt" the passwords you send on the wire. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "login, wp login form, remote login, encryption"
} |
How to var dump urls for all posts
I need to see all urls of all publish blog posts in the site. How can I get this? I want this for redirecting in .htaccess of old site to new site. This needed in anything page of site.The result is each posts url on a new line. | I've been solved my problem by this query:
SELECT `post_name`
FROM `wp_posts`
WHERE `post_content` IS NOT NULL
AND `post_title` IS NOT NULL
AND `post_status` = 'publish'
AND `post_type` = 'post' | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -4,
"tags": "posts, pre get posts"
} |
Insert shortcode in widget area
I enabled the Insert Pages plugin wich allows to create a shortcode for a given page e.g.: `[insert page='7' display='all']`.
See my capture of the setting of the plugin: <
Then, I added a "Text Html" widget to the Sidebar area with this text: `[insert page='7' display='all']`. What I need is to show the full content of that page (page id =7) in this area.
But the page is not shown, I just see the shortcode as it: [insert page='7' display='all'].
What am I missing here? | Shortcodes are not parsed in widget text - you need to tell WordPress to do so:
add_filter( 'widget_text', 'do_shortcode' );
Place it in your theme's `functions.php` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "shortcode"
} |
How to check post type (to include custom css)
I need to check the post type. If I put this in my functions file:
echo "the post type is" . get_post_type();
the message just becomes: "the post type is". Is the post type checked to early? Do have to put it in some action to check for it at a later time?
(Consequently this didn't work:)
if (get_post_type() == 'product'){
wp_enqueue_style( 'css_products.css', get_stylesheet_uri().'assets/css/css_products.css', false );
} | Yes too early is probably why, the global `$post` variable is not populated yet. Try hooking to a later action (I think `init` at the very least):
add_action('wp_enqueue_scripts','enqueue_product_styles');
function enqueue_product_styles() {
if (get_post_type() == 'product'){
wp_enqueue_style( 'css_products.css', get_stylesheet_directory_uri().'/assets/css/css_products.css', false );
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, customization"
} |
Add content in custom post type page after the title and before columns
I found here on WPSE that you can add content before post title in the post page, and in custom post type pages
add_action( 'load-edit.php', function(){
$screen = get_current_screen();
// Only edit post screen:
if( 'edit-reservation' === $screen->id )
{
// Before:
add_action( 'all_admin_notices', function(){
echo '<p>Greetings from <strong>all_admin_notices</strong>!</p>';
});
}
});
Which works in my reservation custom post type. But I'm wondering if it's possible to output content after the title, but before table with custom post types?
;
## Example
For the `edit-post` screen, the filter is `views_edit-post`:
/**
* Display HTML after the 'Posts' title
* where we target the 'edit-post' screen
*/
add_filter( 'views_edit-post', function( $views )
{
echo '<p>Greetings from <strong>views_edit-post</strong></p>';
return $views;
} );
and this will display as:
:
confirmation-tt5,
confirmation-556,
Should I just create a `single-confirmation` or will I need a custom filter? | We can make use of the `page_template` filter to achieve this. All we need to do is to make sure that `confirmation` is the first word in the page page title
add_filter( 'page_template', function ( $template )
{
// Get the current page object
$post = get_queried_object();
/**
* Get the first instance of confirmation, if it is not 0, bail
* We will be using the page name, which is the slug
*/
if ( 0 !== stripos( $post->post_name, 'confirmation' ) )
return $template;
// We have confimation as first word, lets continue
$locate_template = locate_template( 'page-confirmation.php' );
// Check if $locate_template is not empty, if so, bail
if ( !$locate_template )
return $template;
// page-confirmation.php exist, return it
return $locate_template;
}); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "page template"
} |
What's the difference between the permissions "edit_published_posts" and "edit_posts"
What's the difference between the permissions "edit_published_posts" and "edit_posts"? It's not clear on the wordpress manual. | The difference is that 'edit_published_posts' allows the user to edit posts whose status has been set to 'published', in other words, live content. The 'edit_posts' allows users to edit unpublished (e.g. draft) posts.
For most bloggers, the distinction is irrelevant, but if you're using Wordpress for a company or a newsroom, you may want all posts to be reviewed by an editor prior to release. In that case you would also not want anyone but an editor making changes to live content. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 5,
"tags": "permissions"
} |
Which hook for processing plugin page form data?
Which hook should I use for processing form data from my plugin pages. I currently use _"admin_init"_. Is that correct? Was this hook intended to be used this way? | if you're processing data submitted from a custom form, then I'd say the init hook is the best hook to use. See example 1. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "admin, dashboard, admin init"
} |
I just updated my SSL certificate and now my site looses formatting when
Ever Since I update my SSL certificate, my site will not open properly unless I do not "not secure" the connection. If secured, the page looses all formatting. I believe my SSL is not properly setup. Is this true? Please help!
 and pass their email address as a variable in the url. The reason I want to pass the email address as a variable in the url is so that the user doesn't have to re-enter this information.
How would I go about doing this? I have gotten the variable to show in the url but am having trouble retrieving it and saving to a variable. | The first form:
<form method="post" action="some-url.php">
<input type="email" placeholder="Email address" value="" name="email">
<input type="submit" value="Submit" name="email-submit">
</form>
Then in some-url.php:
if( isset($_POST['email'] )
$email = $_POST['email']
The post method would be preferred here since it won't create server log entries that include the user's email address.
You should also do this over SSL since you are collecting "name, age, etc." | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "urls, query variable"
} |
How to add conditionals for IE browsers between certain versions?
I know that `wp_script_add_data` and `wp_style_add_data` are the correct functions for adding IE conditionals.
**_For example, this:_**
wp_script_add_data( 'foo', 'conditional', 'lt IE 9' );
**_Would get you this:_**
<!--[if (lt IE 9)]>
<script type="text/javascript" src="foo.js"></script>
<![endif]-->
* * *
**However, what if I want to do this (IE browsers _between_ certain versions)?**
<!--[if (gt IE 6)&(lt IE 9)]>
<script type="text/javascript" src="foo.js"></script>
<![endif]--> | Could you not just pass the different string?
wp_script_add_data( 'foo', 'conditional', '(gt IE 6)&(lt IE 9)' );
Which by the way is probably the same as:
wp_script_add_data( 'foo', 'conditional', '(IE 7)|(IE 8)' );
IE conditionals are pretty unreliable so need to be tested. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp enqueue script, conditional tags, wp enqueue style"
} |
Grouped Custom Meta Fields without plugin
I need to add grouped multiple custom metas. I did it with CMBII plugin. But if it's possible, I want to create it without any plugin. | stick with cmb2 -- there is another method of displaying and then saving meta data, but it's a PAIN and loads your functions file. the plugin pretty much has no effect on the front end of the site -- it'll also make your meta boxes a lot cleaner and consistent-looking | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -2,
"tags": "custom field"
} |
My Wordpress site hacked with unwanted popups
I have a woo-commerce shop on my wordpress but I've been attacked by some kind of hack. As you can see in the image there are lots of popup link on top of my site . How can I clean this ? I do not have any backup . . I expected excerpt will be shown on front page like the method above, but instead the excerpt is shown over the full post, both are displayed !!
I need the manual excerpt (like in method 2) but to display only the excerpt on the front page without the full post.
How to achieve that (without coding if possible) for the end-user?
Notes: * I'm using the latest version of WP (4.4.2). * Theme used is "Twenty Sixteen". * Default plugins only are installed. | For the record and for anyone who comes next.
I found the issue. Although the excerpts is a native WordPress feature it is not supported -in the right way- by the "official" "pre-installed" themes like the twenty-xxx series.
Not Supporting (in the right way) a native feature isn't a common sense!!! It is a bad behavior of the official theme to display the excerpt above the full-post!!.
Excerpts supported correctly by some third party themes like FlatBox: <
For whom tried to help me I appreciate your effort and thank you. | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 3,
"tags": "excerpt"
} |
Wordpress wp-admin suddenly lost its style
**NB:** I originally posted this on SO, but I was recommended to try here - sorry for the duplicate!
I'm really baffled about this. In the last couple of days (since I was using the site last), my Wordpress install has suddenly lost almost all of its formatting (only the top bar seems to work.
;
.
Looks like the solution was to re-install. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "wp admin, css"
} |
Best method to make posts searchable, sortable and filterable - custom field, tag or category?
I'm wanting to create/modify either the existing post type, or create a new post type to be searchable, sortable and filterable by the following fields:
* Country from:
* Country to:
* Activity:
Ideally I would like them to be:
* Searchable, e.g. I could search for posts from Country X to Country Y with activity Z
* Listable, to be accessible via dropdown menus
What would be the best method of implementing this? A custom taxonomy?
Through hierarchical categories? Using custom post data?
Thanks
Update:
I think the following is the best approach:
Custom post type that uses a custom taxonomy for each data point. | I ended up doing the following:
Custom post type for Deals:
Custom taxonomies for Countries and Activities, then a relational link between country from and country to as custom fields to the taxonomy :) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, categories, custom taxonomy"
} |
Can't access Admin Panel
In Settings > General, I change my site to be ` and now when I go to `/wp-admin` I get a 404 Not Found.
Is there a way I can revert this? I tried Googling but found nothing :( | You cannot revert this. You will need to export your database via PhpMyAdmin and find all of the "HTTPS" instances and replace them with "HTTP". I would suggest using something like Dreamweaver or Notepad++ to 'find and replace all'. After you have done that, import your database again. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "https"
} |
creating a custom shop page display on archive woocommerce
Hello guys how are you? i am not that good at developing websites and i need to have more experience. can you guys help me? i had an idea on the screenshot i have on the link below. as you can see i want the circled one to be a category and the other non circled are all the products you have. i tried everything from plugins to editing a custom product archive but it really wont budge. i just want to know if my idea is applicable, doable or not.
Thank you guys always for helping people on codes. You guys are the best.
Thank you in advance. :)
| First of all, yes, and there are many ways to achieve this. The first thing you will want to do is create a child theme or plugin. One of those two is where you will be adding your code...
This can be done by using wp action _pre_get_posts_ there is a great post that Remi Corson has here to explain more about modifying if only on the archive page:
from on of his examples (with a little mod):
// Load our function when hook is set
add_action( 'pre_get_posts', 'rc_modify_query_get_design_projects' );
function rc_modify_query_get_design_projects( $query ) {
// Check if on frontend and main query is modified
if( ! is_admin() && $query->is_main_query() && is_post_type_archive( 'product' ) ) {
$query->set( 'cat', '20' ); // whatever your category id is here
}
}
something like the above (very much untested in your environment), but I think you can get the idea here... | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, customization, woocommerce offtopic"
} |
Is revealing just the AUTH_KEY a security issue?
I am troubleshooting a Wordpress plugin issue. It is a plugin that generates a zip file of existing files on the server and returns a link to download the file.
The plugin
<
The plugin add-on that is the source of the issue.
<
The plugin creates a directory to save the generated zip file using the AUTH_KEY as the name of the directory. When the url is returned to the client it contains the AUTH_KEY as part of its path.
$zip_path = '' . SP_CDM_UPLOADS_DIR_URL . '' . AUTH_KEY. '/'
This returns a url similar to the following:
If any of the characters in the AUTH_KEY are not allowed in a url the download will return a 404. This is happening but that can easily be fixed by changing the AUTH_KEY to a string that will work in a url. My worry is the fact that it contains the AUTH_KEY.
Is revealing the AUTH_KEY by itself a reason for concern? | Well, `AUTH_KEY` and it´s brothers where introduced in WordPress 2.6 to improve safety for logged in users. They are used to encrypt and validate the information in your backend login cookie.
While revealing the `AUTH_KEY` alone might not be a real security issue, you should nevertheless not output/use this anywhere to give less surface for attacks.
Furthermore I don´t see why you would use the `AUTH_KEY` to prepare a folder/download link. I think it would be much better to use something like `time()` to generate folder names if you want randomness or uniqueness or whatever without compromising the security of the system.
**Update:** I opened a thread in the plugins support area. Let´s see if the author responds to it. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "plugins, urls, security"
} |
How to stop the continuation of posts on the second loop from where the first ended
I recently built a theme that has slider on the index page that loops through posts to create the content of the slider(used increment to stop at five posts only), but for some reason that is just above me,the posts on the next loop I used to get latest posts, picks up from where the slider loop ended, does any one have an idea on how to make the second loop start all over from the first post, thanks in advance to any one who will answer. | Add
wp_reset_postdata();
After your loop that gets the 5 posts for your slider. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "loop"
} |
Make posts non-sticky
I have around 200 posts. I want to make all posts non-sticky except 4 posts. I know the id of those 4 posts. How can I do it? Using plugin or sql query? | You can use a simple script which you run once and remove. The idea is to replace the sticky post array with an array of the 4 desired ID's
**PHP 5.4+ version - short array syntax**
add_action( 'init', function ()
{
// Define our new array
$stickies = [1,2,3,4]; // Change to match your own ID's
// Update the sticky posts option
update_option(
'sticky_posts', // Option name
$stickies // New value
);
}, PHP_INT_MAX );
**Pre PHP5.4 version**
add_action( 'init', function ()
{
// Define our new array
$stickies = array( 1,2,3,4 ); // Change to match your own ID's
// Update the sticky posts option
update_option(
'sticky_posts', // Option name
$stickies // New value
);
}, PHP_INT_MAX ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "sticky post"
} |
Edit a WordPress site without the username and password?
I am trying to edit a website for a client who had the website built for them a few years ago. They've given me access their website server, and I can see the website is using WordPress from the folder structure. I tried adding /wp-admin to the website, however I am getting a "Page not found" error.
Is there a way for me to edit the WordPress site without being able to access the WordPress admin login page? I do have access to the server in which the site is stored on.
Or could I reset the WordPress login credentials somehow, and find where the login screen is? | First, you can check installed wordpress (wp-content).
Your login screen is here: <
If you have database access. You can update password (MD5) in database.
Or if you have not access. You can try code in `functions.php` only one time.
<?php
$user_id = 1;
$password = 'HelloWorld';
wp_set_password( $password, $user_id );
?> | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "wp admin, login"
} |
mu-plugins is there something special I need to do to make it work?
I created a mu-plugins directory in wp-content
As long as it is empty, I have no issue, but the moment I put a file in there, even if the file is like this:
filename: somecode.php
filecontent:
<?php
?>
and that be all, no blank spaces or lines after the closing php tag, or after the first line of <?php
I get issues with the CSS on the website, stuff not working right.
I have no clue as to why it would be doing that. I even put the file in there blank, not even a single blank line. Same thing. Once I delete the file, everything is fine.
I've tested LOTS of stuff, any file in that directory breaks the website.
I've even tested it with different themes. Same thing.
So am I doing something wrong?
All I did was create the mu-plugins directory. was I supposed to do something extra? Like put any code in my wordpress installation?
Please help.
-Richard | The file you put in there is automatically loaded and executed by PHP before any of the normal plugins are loaded.
The issue you're seeing is because you have a "malformed" PHP file, in that you end with a closing PHP tag `?>`. If there is anything else after this closing tag, even only a line-break, this causes PHP to immediately send its headers and start echoing output.
If you file immediately starts with the opening PHP tag `<?php` and does not include a closing tag `?>`, you should not see this issue.
The same problem was when you had an empty file. This was interpreted by PHP as a normal HTML file (PHP is a preprocessor for HTML) and simply echoed. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "mu plugins"
} |
Can wp_get_image_editor convert to icon?
I have a very simple question regarding **wp_get_image_editor** (< I can crop, resize and save an image like this:
$image = wp_get_image_editor( 'example_1.jpg' );
$image->resize( 32, 32, true );
$image->save( $path . '/test.png' ); // Works with jpg/gif/png
It works perfectly. I can convert a JPG file to GIF or PNG (and vice versa), but I don't seem to be able to conver an image to a .ico file. So a code like:
$image->save( $path . '/test.ico' );
Doesn't output any image nor any error/notice. So at this point I wonder: can wp_get_image_editor actually convert to .ico files (and if so, how, what am I missing/doing wrong), or it can't be done?
Thanks in advance! | No. At least I've never saw it.
**Although** I believe that you can tailor some solution. Since WordPress 3.5 in `WP_Image_Editor` is added support for Imagick by default (which is a wrapper to the ImageMagick library). You can check `class-wp-image-editor-imagick.php` to see how it's integrated and if you have ImageMagick installed on your server, probably you can tailor something. But I believe it will probably be an overkill for a small set of .ico files. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images, icon"
} |
wp.template() Not a function
When I console.log(wp) the object only includes: -wp.emoji -wp.heartbeat -wp.svgPainter
Script is loaded in the footer and last in the DOM. What am I missing? | Ah, I get it. When you enqueue your admin script, add 'wp-util' as a dependancy.
wp_enqueue_script( 'script_handle', plugin_dir_url( __FILE__ ) . 'script.js', array( 'jquery', 'wp-util' ), '1.0', true ); | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 1,
"tags": "admin, javascript"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.