qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
205,814 |
<p>I am trying to figure out how to display a video on the homepage for users who have not logged in using the <code>functions.php</code> file. I am using a Genesis theme.</p>
|
[
{
"answer_id": 205816,
"author": "Benjamin Love",
"author_id": 81800,
"author_profile": "https://wordpress.stackexchange.com/users/81800",
"pm_score": 2,
"selected": false,
"text": "<p>I'm assuming you already know how to get your popup video working, and you want to know how to make sure only people who aren't logged in see the video. You can add this to your template file (footer.php is probably best):</p>\n\n<pre><code><?php\n if (is_front_page() && !is_user_logged_in()) {\n //video popup content\n }\n?>\n</code></pre>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/is_user_logged_in\" rel=\"nofollow\">WP: is_user_logged_in() »</a></li>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/is_front_page\" rel=\"nofollow\">WP: is_front_page() »</a></li>\n</ul>\n"
},
{
"answer_id": 205874,
"author": "Naser",
"author_id": 81706,
"author_profile": "https://wordpress.stackexchange.com/users/81706",
"pm_score": 0,
"selected": false,
"text": "<p>Hello Try to add above code with youtube video link with no luck.</p>\n\n<p>if (is_front_page() && !is_user_logged_in()) {?></p>\n\n\n \n\n\n<p>\n"
}
] |
2015/10/17
|
[
"https://wordpress.stackexchange.com/questions/205814",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81706/"
] |
I am trying to figure out how to display a video on the homepage for users who have not logged in using the `functions.php` file. I am using a Genesis theme.
|
I'm assuming you already know how to get your popup video working, and you want to know how to make sure only people who aren't logged in see the video. You can add this to your template file (footer.php is probably best):
```
<?php
if (is_front_page() && !is_user_logged_in()) {
//video popup content
}
?>
```
* [WP: is\_user\_logged\_in() Β»](https://codex.wordpress.org/Function_Reference/is_user_logged_in)
* [WP: is\_front\_page() Β»](https://codex.wordpress.org/Function_Reference/is_front_page)
|
205,829 |
<p>I am using a global variable that is defining in a function runs in <code>after_setup_theme</code>. This variable is not getting update changes in Theme Customizer. </p>
<p><strong>Let me explain this with an example:</strong></p>
<pre><code>add_action( 'customize_register', "example_customizer_register");
function example_customizer_register($wp_customize) {
$wp_customize->add_setting( 'example_settings[example-variable]', array(
'type' => 'option',
'default' => false,
'sanitize_callback' => 'esc_attr'
) );
$wp_customize->add_control( 'example_settings[example-variable]', array(
'label' => 'Example Setting',
'type' => 'checkbox',
'section' => 'title_tagline',
) );
}
add_action("after_setup_theme", "example_after_setup_theme");
function example_after_setup_theme(){
global $example_settings;
$example_settings = get_option( "example_settings", array());
}
add_action("wp_head", "example_wp_head");
function example_wp_head(){
global $example_settings;
if (isset($example_settings["example-variable"]) && true == $example_settings["example-variable"]) {
echo "Example Setting";
}
}
</code></pre>
<p>This code is adding an example setting in Site Identity section in Theme Customizer which is not working. If i change;</p>
<pre><code>add_action("after_setup_theme", "example_after_setup_theme");
</code></pre>
<p>to</p>
<pre><code>add_action("wp", "example_after_setup_theme");
</code></pre>
<p>Its working. But i need it in <code>after_setup_theme</code>. Any ideas for solution?</p>
|
[
{
"answer_id": 205828,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": true,
"text": "<p>Your loop on <code>page.php</code> doesn't loop through all the pages on the site. It loops though all the pages returned by the main query and stored in the <code>$wp_query</code> global variable, which is how all of the primary WordPress \"pages\" work including the post archive pages, category, tag pages, etc. For any one \"page\" only one page will be in the <code>$wp_query</code> global so you only see one.</p>\n\n<p>While the details can get complicated, what happens with a page load in WordPress is that the <code>WP_Query</code> class gets instantiated fairly early and it parses the url being loaded and works out what posts to query. That information is shoved into the <code>wp_query</code> global variable and is accessed by numerous bits of code thereafter (which is why you don't really ever want to alter that variable manually or via <code>query_posts()</code>). It is a wildly complicated mechanism which you can see here: <a href=\"https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-includes/query.php#L1448\" rel=\"nofollow\">https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-includes/query.php#L1448</a></p>\n"
},
{
"answer_id": 205837,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>A shorter/simplified version of @s_ha_dum's answer.</p>\n\n<p>Running the templates to do the actual outputting of the HTML is the last thing wordpress does. Before getting there, wordpress parers the URL and based on that it determines the specific content that will be displayed. It is not really open ended, although plugins can extend the loop to do any weird stuff, it is fully determined based on the URL.</p>\n"
}
] |
2015/10/17
|
[
"https://wordpress.stackexchange.com/questions/205829",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1372/"
] |
I am using a global variable that is defining in a function runs in `after_setup_theme`. This variable is not getting update changes in Theme Customizer.
**Let me explain this with an example:**
```
add_action( 'customize_register', "example_customizer_register");
function example_customizer_register($wp_customize) {
$wp_customize->add_setting( 'example_settings[example-variable]', array(
'type' => 'option',
'default' => false,
'sanitize_callback' => 'esc_attr'
) );
$wp_customize->add_control( 'example_settings[example-variable]', array(
'label' => 'Example Setting',
'type' => 'checkbox',
'section' => 'title_tagline',
) );
}
add_action("after_setup_theme", "example_after_setup_theme");
function example_after_setup_theme(){
global $example_settings;
$example_settings = get_option( "example_settings", array());
}
add_action("wp_head", "example_wp_head");
function example_wp_head(){
global $example_settings;
if (isset($example_settings["example-variable"]) && true == $example_settings["example-variable"]) {
echo "Example Setting";
}
}
```
This code is adding an example setting in Site Identity section in Theme Customizer which is not working. If i change;
```
add_action("after_setup_theme", "example_after_setup_theme");
```
to
```
add_action("wp", "example_after_setup_theme");
```
Its working. But i need it in `after_setup_theme`. Any ideas for solution?
|
Your loop on `page.php` doesn't loop through all the pages on the site. It loops though all the pages returned by the main query and stored in the `$wp_query` global variable, which is how all of the primary WordPress "pages" work including the post archive pages, category, tag pages, etc. For any one "page" only one page will be in the `$wp_query` global so you only see one.
While the details can get complicated, what happens with a page load in WordPress is that the `WP_Query` class gets instantiated fairly early and it parses the url being loaded and works out what posts to query. That information is shoved into the `wp_query` global variable and is accessed by numerous bits of code thereafter (which is why you don't really ever want to alter that variable manually or via `query_posts()`). It is a wildly complicated mechanism which you can see here: <https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-includes/query.php#L1448>
|
205,832 |
<p>I'm using the following code at the top of my index.php page in my theme and it never hits the <code>is_single()</code> code even on single posts. </p>
<pre><code>if ( have_posts() ) {
echo "****************we have posts";
if ( is_single() ) {
echo "******************It's single";
}
while ( have_posts() ) {
the_post();
echo "<br >******************after the_post(): " . $post->ID;
if ( is_single() ) {
echo "******************It's single";
//$myHTML = get_post_meta($post->ID, 'html', true);
if (false && $myHTML) {
echo $myHTML;
die();
}
else {
//
}
}
}
}
else {
echo "******************we have no posts";
}
</code></pre>
|
[
{
"answer_id": 205833,
"author": "1.21 gigawatts",
"author_id": 29247,
"author_profile": "https://wordpress.stackexchange.com/users/29247",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like it's not hitting that code because it's redirecting to <code>single.php</code>. I didn't have this in my other theme so it was working there. </p>\n\n<p>I have to delete <code>single.php</code> so the logic workflow will work there or move my code to <code>single.php</code>. </p>\n"
},
{
"answer_id": 205844,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>Your question and answer comes down to template hierarchy and how it works, and it is really really useful to know the basics here.</p>\n\n<p>I'm not going to go into details as I will need to write a short story, but here are the basics:</p>\n\n<ul>\n<li><p>Wordpress uses a very strict hierarchy for loading templates on a specific page request. This hierarchy is known as the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow\">template hierarchy</a> which you will <strong>have to</strong> work through at your own pace. This hierarchy remains constant and never change, except if the core developers changes it in newer versions (<em>like the introduction of some new extra templates in versions 4.3 and 4.4</em>), or if it is changes via one of the template filters. </p></li>\n<li><p>Wordpress is coded in such a way that the only template you will ever need to display any page on is <code>index.php</code>. This template is the ultimate fallback template for any page request and is the template lowest in any given hierarchy. This will in all probability never change.</p></li>\n<li><p>The template highest in the hierarchy will be loaded first, if found, otherwise, the first available template lower down in the hierarchy will be loaded. As it goes, if no special template is found, Wordpress will always load <code>index.php</code>. Any other custom template can however be used in stead of these through the specific template filters provided</p></li>\n<li><p>Any other template in a specific hierarchy, except <code>index.php</code> (<em>which is a must-have template</em>), is the nice-to-have templates. They are only there for convenience and their usage are optional. These template only serves to create a specific look and feel on the front end of the site for a specific page request through special functions or CSS and/or JS effects. </p></li>\n</ul>\n\n<p>To put everything in perspective, lets look at your specific case. Lets look at the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post\" rel=\"nofollow\">template hierarchy for single posts</a></p>\n\n<blockquote>\n <p>The single post template file is used to render a single post.\n WordPress uses the following path:</p>\n \n <ol>\n <li><p><strong><code>single-{post-type}-{slug}.php</code></strong> β (Since 4.4) First, WordPress looks for\n a template for the specific post. For example, if post type is product\n and the post slug is dmc-12, WordPress would look for\n single-product-dmc-12.php. </p></li>\n <li><p><strong><code>single-{post-type}.php</code></strong> β If the post type\n is product, WordPress would look for single-product.php. </p></li>\n <li><p><strong><code>single.php</code></strong> β\n WordPress then falls back to single.php. </p></li>\n <li><p><strong><code>singular.php</code></strong> β Then it falls\n back to singular.php. </p></li>\n <li><p><strong><code>index.php</code></strong> β Finally, as mentioned above,\n WordPress ultimately falls back to index.php.</p></li>\n </ol>\n</blockquote>\n\n<p>As you can see, in the above hierarchy, <code>single.php</code> is a higher ranking template than <code>index.php</code>, and since <code>single.php</code> exist in your theme, Wordpress will always load <code>single.php</code>, and never <code>index.php</code> (<em>or even <code>singular.php</code></em>) for a single post page (<em>except if this behavior is interfered with through the <code>single_template</code> filter</em>).</p>\n"
}
] |
2015/10/18
|
[
"https://wordpress.stackexchange.com/questions/205832",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29247/"
] |
I'm using the following code at the top of my index.php page in my theme and it never hits the `is_single()` code even on single posts.
```
if ( have_posts() ) {
echo "****************we have posts";
if ( is_single() ) {
echo "******************It's single";
}
while ( have_posts() ) {
the_post();
echo "<br >******************after the_post(): " . $post->ID;
if ( is_single() ) {
echo "******************It's single";
//$myHTML = get_post_meta($post->ID, 'html', true);
if (false && $myHTML) {
echo $myHTML;
die();
}
else {
//
}
}
}
}
else {
echo "******************we have no posts";
}
```
|
Your question and answer comes down to template hierarchy and how it works, and it is really really useful to know the basics here.
I'm not going to go into details as I will need to write a short story, but here are the basics:
* Wordpress uses a very strict hierarchy for loading templates on a specific page request. This hierarchy is known as the [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) which you will **have to** work through at your own pace. This hierarchy remains constant and never change, except if the core developers changes it in newer versions (*like the introduction of some new extra templates in versions 4.3 and 4.4*), or if it is changes via one of the template filters.
* Wordpress is coded in such a way that the only template you will ever need to display any page on is `index.php`. This template is the ultimate fallback template for any page request and is the template lowest in any given hierarchy. This will in all probability never change.
* The template highest in the hierarchy will be loaded first, if found, otherwise, the first available template lower down in the hierarchy will be loaded. As it goes, if no special template is found, Wordpress will always load `index.php`. Any other custom template can however be used in stead of these through the specific template filters provided
* Any other template in a specific hierarchy, except `index.php` (*which is a must-have template*), is the nice-to-have templates. They are only there for convenience and their usage are optional. These template only serves to create a specific look and feel on the front end of the site for a specific page request through special functions or CSS and/or JS effects.
To put everything in perspective, lets look at your specific case. Lets look at the [template hierarchy for single posts](https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post)
>
> The single post template file is used to render a single post.
> WordPress uses the following path:
>
>
> 1. **`single-{post-type}-{slug}.php`** β (Since 4.4) First, WordPress looks for
> a template for the specific post. For example, if post type is product
> and the post slug is dmc-12, WordPress would look for
> single-product-dmc-12.php.
> 2. **`single-{post-type}.php`** β If the post type
> is product, WordPress would look for single-product.php.
> 3. **`single.php`** β
> WordPress then falls back to single.php.
> 4. **`singular.php`** β Then it falls
> back to singular.php.
> 5. **`index.php`** β Finally, as mentioned above,
> WordPress ultimately falls back to index.php.
>
>
>
As you can see, in the above hierarchy, `single.php` is a higher ranking template than `index.php`, and since `single.php` exist in your theme, Wordpress will always load `single.php`, and never `index.php` (*or even `singular.php`*) for a single post page (*except if this behavior is interfered with through the `single_template` filter*).
|
205,872 |
<p>I need the text seen in light gray at the top of the header to be below the site title/tagline but above the tabbed navigation:</p>
<p><a href="http://devtest.lcnlit.org" rel="nofollow">devtest.lcnlit.org</a></p>
<p>I would prefer learning to do it the proper way (calling it in a function?), but I will use hard-coding if I have to. I currently have the text hardcoded under cryout-branding-hook, but I don't really understand what all of the hooks in the header do, so can't figure out where to properly place the text in my child theme header.</p>
<p>Thank you for your help.</p>
<p>Here is the header.php file:</p>
<pre><code><?php
/**
* The Header
*
* Displays all of the <head> section and everything up till <div id="main">
*
* @package Cryout Creations
* @subpackage mantra
* @since mantra 0.5
*/
?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<title><?php wp_title( '', true, 'right' ); ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=<?php bloginfo( 'charset' ); ?>" />
<?php cryout_seo_hook(); ?>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<?php
cryout_header_hook();
wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<?php cryout_body_hook(); ?>
<div id="wrapper" class="hfeed">
<?php cryout_wrapper_hook(); ?>
<header id="header">
<div id="masthead">
<div id="branding" role="banner" >
<?php cryout_branding_hook();?>
<div id="blurb"> LCN provides ABE (adult basic education), ESOL (English for Speakers of other languages), and GED instruction at little or no cost to adult learners in our community. If you need instruction or would like to be a volunteer tutor, please call 610-292-8515.</div>
<div style="clear:both;"></div>
</div><!-- #branding -->
<nav id="access" class="jssafe" role="navigation">
<?php cryout_access_hook();?>
</nav><!-- #access -->
</div><!-- #masthead -->
<div style="clear:both;"> </div>
</header><!-- #header -->
<div id="main">
<div id="forbottom" >
<?php cryout_forbottom_hook(); ?>
<div style="clear:both;"> </div>
<?php cryout_breadcrumbs_hook();?>
</code></pre>
|
[
{
"answer_id": 205833,
"author": "1.21 gigawatts",
"author_id": 29247,
"author_profile": "https://wordpress.stackexchange.com/users/29247",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like it's not hitting that code because it's redirecting to <code>single.php</code>. I didn't have this in my other theme so it was working there. </p>\n\n<p>I have to delete <code>single.php</code> so the logic workflow will work there or move my code to <code>single.php</code>. </p>\n"
},
{
"answer_id": 205844,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>Your question and answer comes down to template hierarchy and how it works, and it is really really useful to know the basics here.</p>\n\n<p>I'm not going to go into details as I will need to write a short story, but here are the basics:</p>\n\n<ul>\n<li><p>Wordpress uses a very strict hierarchy for loading templates on a specific page request. This hierarchy is known as the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow\">template hierarchy</a> which you will <strong>have to</strong> work through at your own pace. This hierarchy remains constant and never change, except if the core developers changes it in newer versions (<em>like the introduction of some new extra templates in versions 4.3 and 4.4</em>), or if it is changes via one of the template filters. </p></li>\n<li><p>Wordpress is coded in such a way that the only template you will ever need to display any page on is <code>index.php</code>. This template is the ultimate fallback template for any page request and is the template lowest in any given hierarchy. This will in all probability never change.</p></li>\n<li><p>The template highest in the hierarchy will be loaded first, if found, otherwise, the first available template lower down in the hierarchy will be loaded. As it goes, if no special template is found, Wordpress will always load <code>index.php</code>. Any other custom template can however be used in stead of these through the specific template filters provided</p></li>\n<li><p>Any other template in a specific hierarchy, except <code>index.php</code> (<em>which is a must-have template</em>), is the nice-to-have templates. They are only there for convenience and their usage are optional. These template only serves to create a specific look and feel on the front end of the site for a specific page request through special functions or CSS and/or JS effects. </p></li>\n</ul>\n\n<p>To put everything in perspective, lets look at your specific case. Lets look at the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post\" rel=\"nofollow\">template hierarchy for single posts</a></p>\n\n<blockquote>\n <p>The single post template file is used to render a single post.\n WordPress uses the following path:</p>\n \n <ol>\n <li><p><strong><code>single-{post-type}-{slug}.php</code></strong> β (Since 4.4) First, WordPress looks for\n a template for the specific post. For example, if post type is product\n and the post slug is dmc-12, WordPress would look for\n single-product-dmc-12.php. </p></li>\n <li><p><strong><code>single-{post-type}.php</code></strong> β If the post type\n is product, WordPress would look for single-product.php. </p></li>\n <li><p><strong><code>single.php</code></strong> β\n WordPress then falls back to single.php. </p></li>\n <li><p><strong><code>singular.php</code></strong> β Then it falls\n back to singular.php. </p></li>\n <li><p><strong><code>index.php</code></strong> β Finally, as mentioned above,\n WordPress ultimately falls back to index.php.</p></li>\n </ol>\n</blockquote>\n\n<p>As you can see, in the above hierarchy, <code>single.php</code> is a higher ranking template than <code>index.php</code>, and since <code>single.php</code> exist in your theme, Wordpress will always load <code>single.php</code>, and never <code>index.php</code> (<em>or even <code>singular.php</code></em>) for a single post page (<em>except if this behavior is interfered with through the <code>single_template</code> filter</em>).</p>\n"
}
] |
2015/10/18
|
[
"https://wordpress.stackexchange.com/questions/205872",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29370/"
] |
I need the text seen in light gray at the top of the header to be below the site title/tagline but above the tabbed navigation:
[devtest.lcnlit.org](http://devtest.lcnlit.org)
I would prefer learning to do it the proper way (calling it in a function?), but I will use hard-coding if I have to. I currently have the text hardcoded under cryout-branding-hook, but I don't really understand what all of the hooks in the header do, so can't figure out where to properly place the text in my child theme header.
Thank you for your help.
Here is the header.php file:
```
<?php
/**
* The Header
*
* Displays all of the <head> section and everything up till <div id="main">
*
* @package Cryout Creations
* @subpackage mantra
* @since mantra 0.5
*/
?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<title><?php wp_title( '', true, 'right' ); ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=<?php bloginfo( 'charset' ); ?>" />
<?php cryout_seo_hook(); ?>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<?php
cryout_header_hook();
wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<?php cryout_body_hook(); ?>
<div id="wrapper" class="hfeed">
<?php cryout_wrapper_hook(); ?>
<header id="header">
<div id="masthead">
<div id="branding" role="banner" >
<?php cryout_branding_hook();?>
<div id="blurb"> LCN provides ABE (adult basic education), ESOL (English for Speakers of other languages), and GED instruction at little or no cost to adult learners in our community. If you need instruction or would like to be a volunteer tutor, please call 610-292-8515.</div>
<div style="clear:both;"></div>
</div><!-- #branding -->
<nav id="access" class="jssafe" role="navigation">
<?php cryout_access_hook();?>
</nav><!-- #access -->
</div><!-- #masthead -->
<div style="clear:both;"> </div>
</header><!-- #header -->
<div id="main">
<div id="forbottom" >
<?php cryout_forbottom_hook(); ?>
<div style="clear:both;"> </div>
<?php cryout_breadcrumbs_hook();?>
```
|
Your question and answer comes down to template hierarchy and how it works, and it is really really useful to know the basics here.
I'm not going to go into details as I will need to write a short story, but here are the basics:
* Wordpress uses a very strict hierarchy for loading templates on a specific page request. This hierarchy is known as the [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) which you will **have to** work through at your own pace. This hierarchy remains constant and never change, except if the core developers changes it in newer versions (*like the introduction of some new extra templates in versions 4.3 and 4.4*), or if it is changes via one of the template filters.
* Wordpress is coded in such a way that the only template you will ever need to display any page on is `index.php`. This template is the ultimate fallback template for any page request and is the template lowest in any given hierarchy. This will in all probability never change.
* The template highest in the hierarchy will be loaded first, if found, otherwise, the first available template lower down in the hierarchy will be loaded. As it goes, if no special template is found, Wordpress will always load `index.php`. Any other custom template can however be used in stead of these through the specific template filters provided
* Any other template in a specific hierarchy, except `index.php` (*which is a must-have template*), is the nice-to-have templates. They are only there for convenience and their usage are optional. These template only serves to create a specific look and feel on the front end of the site for a specific page request through special functions or CSS and/or JS effects.
To put everything in perspective, lets look at your specific case. Lets look at the [template hierarchy for single posts](https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post)
>
> The single post template file is used to render a single post.
> WordPress uses the following path:
>
>
> 1. **`single-{post-type}-{slug}.php`** β (Since 4.4) First, WordPress looks for
> a template for the specific post. For example, if post type is product
> and the post slug is dmc-12, WordPress would look for
> single-product-dmc-12.php.
> 2. **`single-{post-type}.php`** β If the post type
> is product, WordPress would look for single-product.php.
> 3. **`single.php`** β
> WordPress then falls back to single.php.
> 4. **`singular.php`** β Then it falls
> back to singular.php.
> 5. **`index.php`** β Finally, as mentioned above,
> WordPress ultimately falls back to index.php.
>
>
>
As you can see, in the above hierarchy, `single.php` is a higher ranking template than `index.php`, and since `single.php` exist in your theme, Wordpress will always load `single.php`, and never `index.php` (*or even `singular.php`*) for a single post page (*except if this behavior is interfered with through the `single_template` filter*).
|
205,876 |
<p><em>FYI: This has been also posted <a href="https://stackoverflow.com/questions/33202955/which-ways-can-be-used-to-log-in-to-wordpress">here</a> since I'm fairly new to this website and didn't know that the Wordpress part existed. Sorry for the repost.</em></p>
<p>I'm currently trying to tighten the security for a website which is running on <a href="/questions/tagged/wordpress" class="post-tag" title="show questions tagged 'wordpress'" rel="tag">wordpress</a> (seperate installation, not on wordpress.org / .com). I have installed <a href="https://wordpress.org/plugins/wordfence/" rel="nofollow noreferrer">Wordfence</a> which blocks all IPs which try to use a invalid user name instantly which works quite well (some 200+ blocked IPs / day).</p>
<p>Since our ISP is giving out hostnames like</p>
<pre><code>www-xxx-yyy-zzz.my.isp.tld
</code></pre>
<p>and there are no users which need log in besides me I thought I would add some way to further prevent brute-force attacks.</p>
<p>The WP Codex has a <a href="https://wordpress.org/support/article/brute-force-attacks/#deny-access-to-no-referrer-requests" rel="nofollow noreferrer">section about preventing access to wp-login.php</a> for anyone who's not submitting it the form. In my eyes this should get rid of any scripts which try to brute force their way in like:</p>
<pre><code>www.mydomain.tld/wp-admin.php?log=admin&pwd=alex
</code></pre>
<p>Now for anyone submitting the form this wouldn't work, so I added a part to the top of <code>wp-login.php</code> which would check for the host name and then re-direct if it doesn't match our ISP:</p>
<pre><code><?PHP
if (strpos(gethostbyaddr($_SERVER['REMOTE_ADDR']),'my.isp.tld') == false) {
header('Location: http://www.google.com/');
}
?>
</code></pre>
<p>I checked it and this piece is working fine as well, when I try to access <code>wp-login.php</code> over my mobile it throws me back to Google, additionally I get an e-mail when somebody tries this. So far it's only been 3-4 login attempts I prevented using this method.</p>
<p>Now from my perspective I've taken care of all things, but Wordfence will still send me notifications about blocked log-in attempts.</p>
<p>To see if it helps, I've added the following to the <a href="/questions/tagged/.htaccess" class="post-tag" title="show questions tagged '.htaccess'" rel="tag">.htaccess</a> file which is in the main Wordpress folder, which, to my understanding, should deny all access except when coming from my ISP:</p>
<pre><code><Files "wp-login.php">
order deny,allow
allow from my.isp.tld
</Files>
</code></pre>
<p>Still the e-mails come flying in. Now the question is:</p>
<p>Is there any other way to call <code>wp-login.php</code> in order to try to login which I haven't tought of? It seems that there are still ways which can be used which are not part of the scenarios mentioned above.</p>
<p>As commented in the other question: The IPs with the failed attempts are not spoofed to fit mine.</p>
<p>Any ideas, comments etc. are greatly appreciated.</p>
<p>So long</p>
|
[
{
"answer_id": 205899,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>wrote something long and decided to delete because the Tl;Dr is use a good password and stop pretending to have a knowledge in how to secure sites, you are more likely to bring down the performance of the site (your reverse DNS code) or lock yourself out then actually preventing an attack. </p>\n\n<p>Security is about context, and in the context of wordpress brute force attack is probably the least of your worries, it would not have prevented you to be hacked via \n<a href=\"http://wptavern.com/wordpress-security-alert-new-zero-day-vulnerability-discovered-in-timthumb-script\" rel=\"nofollow\">http://wptavern.com/wordpress-security-alert-new-zero-day-vulnerability-discovered-in-timthumb-script</a></p>\n\n<p>or <a href=\"http://wptavern.com/critical-security-vulnerability-found-in-wordpress-slider-revolution-plugin-immediate-update-advised\" rel=\"nofollow\">http://wptavern.com/critical-security-vulnerability-found-in-wordpress-slider-revolution-plugin-immediate-update-advised</a> </p>\n\n<p>or <a href=\"https://blog.sucuri.net/2015/10/security-advisory-stored-xss-in-jetpack.html\" rel=\"nofollow\">https://blog.sucuri.net/2015/10/security-advisory-stored-xss-in-jetpack.html</a></p>\n\n<p>And before even getting to plugins maybe I should have asked is your hosting secure? (can't find the link and don't remember which big hosting company was hacked)</p>\n"
},
{
"answer_id": 206206,
"author": "MDschay",
"author_id": 82137,
"author_profile": "https://wordpress.stackexchange.com/users/82137",
"pm_score": 1,
"selected": true,
"text": "<p>The answer to my question about other login possibilities was given in <a href=\"https://wordpress.stackexchange.com/questions/204485/brute-force-attack-even-though-it-is-limited-by-ip\">the question posted by birgire</a>.</p>\n\n<p>It turns out that after disabling any remote access to <code>xmlrpc.php</code> the attacks went down to zero.</p>\n\n<p>However this might have <a href=\"https://wordpress.org/support/topic/disabling-xml-rpc-may-damage-jetpack\" rel=\"nofollow noreferrer\">serious consequences</a> on your website since it's used by e.g. <a href=\"/questions/tagged/jetpack\" class=\"post-tag\" title=\"show questions tagged 'jetpack'\" rel=\"tag\">jetpack</a> amongst others and I therefor not recommend it. </p>\n\n<p>As mentioned by Mark Kaplun there are probably other, more serious attacks out there and from analyzing my logs these brute force attacks I've encountered are very basic and wouldn't stand a chance when you did the following:</p>\n\n<ul>\n<li>Change the admin user name to anything else than \"admin\"</li>\n<li>Use proper passwords</li>\n</ul>\n"
}
] |
2015/10/18
|
[
"https://wordpress.stackexchange.com/questions/205876",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82137/"
] |
*FYI: This has been also posted [here](https://stackoverflow.com/questions/33202955/which-ways-can-be-used-to-log-in-to-wordpress) since I'm fairly new to this website and didn't know that the Wordpress part existed. Sorry for the repost.*
I'm currently trying to tighten the security for a website which is running on [wordpress](/questions/tagged/wordpress "show questions tagged 'wordpress'") (seperate installation, not on wordpress.org / .com). I have installed [Wordfence](https://wordpress.org/plugins/wordfence/) which blocks all IPs which try to use a invalid user name instantly which works quite well (some 200+ blocked IPs / day).
Since our ISP is giving out hostnames like
```
www-xxx-yyy-zzz.my.isp.tld
```
and there are no users which need log in besides me I thought I would add some way to further prevent brute-force attacks.
The WP Codex has a [section about preventing access to wp-login.php](https://wordpress.org/support/article/brute-force-attacks/#deny-access-to-no-referrer-requests) for anyone who's not submitting it the form. In my eyes this should get rid of any scripts which try to brute force their way in like:
```
www.mydomain.tld/wp-admin.php?log=admin&pwd=alex
```
Now for anyone submitting the form this wouldn't work, so I added a part to the top of `wp-login.php` which would check for the host name and then re-direct if it doesn't match our ISP:
```
<?PHP
if (strpos(gethostbyaddr($_SERVER['REMOTE_ADDR']),'my.isp.tld') == false) {
header('Location: http://www.google.com/');
}
?>
```
I checked it and this piece is working fine as well, when I try to access `wp-login.php` over my mobile it throws me back to Google, additionally I get an e-mail when somebody tries this. So far it's only been 3-4 login attempts I prevented using this method.
Now from my perspective I've taken care of all things, but Wordfence will still send me notifications about blocked log-in attempts.
To see if it helps, I've added the following to the [.htaccess](/questions/tagged/.htaccess "show questions tagged '.htaccess'") file which is in the main Wordpress folder, which, to my understanding, should deny all access except when coming from my ISP:
```
<Files "wp-login.php">
order deny,allow
allow from my.isp.tld
</Files>
```
Still the e-mails come flying in. Now the question is:
Is there any other way to call `wp-login.php` in order to try to login which I haven't tought of? It seems that there are still ways which can be used which are not part of the scenarios mentioned above.
As commented in the other question: The IPs with the failed attempts are not spoofed to fit mine.
Any ideas, comments etc. are greatly appreciated.
So long
|
The answer to my question about other login possibilities was given in [the question posted by birgire](https://wordpress.stackexchange.com/questions/204485/brute-force-attack-even-though-it-is-limited-by-ip).
It turns out that after disabling any remote access to `xmlrpc.php` the attacks went down to zero.
However this might have [serious consequences](https://wordpress.org/support/topic/disabling-xml-rpc-may-damage-jetpack) on your website since it's used by e.g. [jetpack](/questions/tagged/jetpack "show questions tagged 'jetpack'") amongst others and I therefor not recommend it.
As mentioned by Mark Kaplun there are probably other, more serious attacks out there and from analyzing my logs these brute force attacks I've encountered are very basic and wouldn't stand a chance when you did the following:
* Change the admin user name to anything else than "admin"
* Use proper passwords
|
205,898 |
<p>I tried to add PHP code after the post title in single post pages by adding a filter to <code>functions.php</code>, but this did not work:</p>
<pre><code>function theme_slug_filter_the_content( $content ) {
$custom_content = 'MY CODES';
$custom_content .= $content;
return $custom_content;
}
add_filter( 'the_content', 'theme_slug_filter_the_content' );
</code></pre>
|
[
{
"answer_id": 205955,
"author": "Ashok Dhaduk",
"author_id": 81215,
"author_profile": "https://wordpress.stackexchange.com/users/81215",
"pm_score": 0,
"selected": false,
"text": "<p>See the below code that you needs to write in content.php file</p>\n\n<pre><code>if ( is_single() ) :\n the_title( '<h1 class=\"entry-title\">', '</h1>' );\nelse :\n the_title( sprintf( '<h2 class=\"entry-title\"><a href=\"%s\" rel=\"bookmark\">', esc_url( get_permalink() ) ), '</a></h2>' );\nendif;\n</code></pre>\n\n<p>Here after Or you can add your code.</p>\n\n<p>I hope your single.php file load template function call this content.php file. you can check this on twentyfifteen theme also that comes with default wordpress installation.</p>\n"
},
{
"answer_id": 308318,
"author": "seeker",
"author_id": 77791,
"author_profile": "https://wordpress.stackexchange.com/users/77791",
"pm_score": 1,
"selected": false,
"text": "<p>You need to use <code>the_title</code> filter, not <code>the_content</code>.\nAlso make sure you have <code>the_title()</code> function somewhere in your single post page.\nHere is the code:</p>\n\n<pre><code>function theme_slug_filter_the_content( $title ) {\n $custom_title = 'MY CODES';\n $custom_title .= $title ;\n return $custom_title ;\n}\nadd_filter( 'the_title', 'theme_slug_filter_the_content' );\n</code></pre>\n"
}
] |
2015/10/19
|
[
"https://wordpress.stackexchange.com/questions/205898",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82151/"
] |
I tried to add PHP code after the post title in single post pages by adding a filter to `functions.php`, but this did not work:
```
function theme_slug_filter_the_content( $content ) {
$custom_content = 'MY CODES';
$custom_content .= $content;
return $custom_content;
}
add_filter( 'the_content', 'theme_slug_filter_the_content' );
```
|
You need to use `the_title` filter, not `the_content`.
Also make sure you have `the_title()` function somewhere in your single post page.
Here is the code:
```
function theme_slug_filter_the_content( $title ) {
$custom_title = 'MY CODES';
$custom_title .= $title ;
return $custom_title ;
}
add_filter( 'the_title', 'theme_slug_filter_the_content' );
```
|
205,909 |
<p>I have several pages on my site, and I want to password protect a page which displays the latest posts. Simply going to the admin panel and setting "Visibility: Password protected" isn't doing anything so... Any help?</p>
<p>I am using Wordpress 4.3.1 on a local machine, if that's any use.</p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 205955,
"author": "Ashok Dhaduk",
"author_id": 81215,
"author_profile": "https://wordpress.stackexchange.com/users/81215",
"pm_score": 0,
"selected": false,
"text": "<p>See the below code that you needs to write in content.php file</p>\n\n<pre><code>if ( is_single() ) :\n the_title( '<h1 class=\"entry-title\">', '</h1>' );\nelse :\n the_title( sprintf( '<h2 class=\"entry-title\"><a href=\"%s\" rel=\"bookmark\">', esc_url( get_permalink() ) ), '</a></h2>' );\nendif;\n</code></pre>\n\n<p>Here after Or you can add your code.</p>\n\n<p>I hope your single.php file load template function call this content.php file. you can check this on twentyfifteen theme also that comes with default wordpress installation.</p>\n"
},
{
"answer_id": 308318,
"author": "seeker",
"author_id": 77791,
"author_profile": "https://wordpress.stackexchange.com/users/77791",
"pm_score": 1,
"selected": false,
"text": "<p>You need to use <code>the_title</code> filter, not <code>the_content</code>.\nAlso make sure you have <code>the_title()</code> function somewhere in your single post page.\nHere is the code:</p>\n\n<pre><code>function theme_slug_filter_the_content( $title ) {\n $custom_title = 'MY CODES';\n $custom_title .= $title ;\n return $custom_title ;\n}\nadd_filter( 'the_title', 'theme_slug_filter_the_content' );\n</code></pre>\n"
}
] |
2015/10/19
|
[
"https://wordpress.stackexchange.com/questions/205909",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82158/"
] |
I have several pages on my site, and I want to password protect a page which displays the latest posts. Simply going to the admin panel and setting "Visibility: Password protected" isn't doing anything so... Any help?
I am using Wordpress 4.3.1 on a local machine, if that's any use.
Thanks in advance!
|
You need to use `the_title` filter, not `the_content`.
Also make sure you have `the_title()` function somewhere in your single post page.
Here is the code:
```
function theme_slug_filter_the_content( $title ) {
$custom_title = 'MY CODES';
$custom_title .= $title ;
return $custom_title ;
}
add_filter( 'the_title', 'theme_slug_filter_the_content' );
```
|
205,940 |
<p>can anyone give me some idea about how I can use the value of <code>wp_logout_url()</code> within the menu creator page of wordpress? As the menu creation page doesn't support php I cannot just put <code>echo wp_logout_url( home_url() )</code> under custom link.</p>
<p>Also I cannot use functions like</p>
<pre><code>add_filter( 'wp_nav_menu_items', 'wti_loginout_menu_link', 10, 2 );
function wti_loginout_menu_link( $items, $args ) {
if ($args->theme_location == 'primary') {
if (is_user_logged_in()) {
$items .= '<li class="right"><a href="'. wp_logout_url() .'">Log Out</a></li>';
} else {
$items .= '<li class="right"><a href="'. wp_login_url(get_permalink()) .'">Log In</a></li>';
}
}
return $items;
}
</code></pre>
<p>because it doesn't fit my need, I have to add the logout link as a dropdown menu not as parent menu and also will show up in certain pages only. I can hel these things if anyone can show me the way how to fetch the <code>wp_logout_url()</code> data within the wp menu creation page.</p>
<p>Any help is highly appreciated.</p>
|
[
{
"answer_id": 205947,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 4,
"selected": true,
"text": "<p>Add submenu with a custom link, <code>/wp-login?action=logout</code>, like the image below:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Aw4k3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Aw4k3.png\" alt=\"enter image description here\"></a></p>\n\n<p>Add code like below in <code>functions.php</code>:</p>\n\n<pre><code>function wpa_remove_menu_item( $items, $menu, $args ) {\n if ( is_admin() || ! is_user_logged_in() ) \n return $items;\n foreach ( $items as $key => $item ) {\n if ( 'Login / Register' == $item->title ) \n unset( $items[$key] );\n if ( 'Logout' == $item->title ) {\n $items[$key]->url = wp_logout_url();\n }\n }\n return $items;\n}\nadd_filter( 'wp_get_nav_menu_items', 'wpa_remove_menu_item', 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 205950,
"author": "iSaumya",
"author_id": 50584,
"author_profile": "https://wordpress.stackexchange.com/users/50584",
"pm_score": 0,
"selected": false,
"text": "<p>Here is what I did to get rid of this issue and I think while solving this issue, I got an idea to fix all similar issues.</p>\n\n<p>I downloaded an amazing plugin called <a href=\"https://wordpress.org/plugins/shortcode-in-menus/\" rel=\"nofollow\">Shortcodes in Menus</a>. </p>\n\n<p>Then in my <code>functions.php</code> file, I created a small shortcode to get rid of this issue:</p>\n\n<pre><code>/* Shortcode to fetch the logout URL */\nadd_shortcode( 'fetch_logout_url', function() {\n return wp_logout_url( home_url() );\n} );\n</code></pre>\n\n<p>Voila! Problem solved, and crazy simple to do. </p>\n"
}
] |
2015/10/19
|
[
"https://wordpress.stackexchange.com/questions/205940",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/50584/"
] |
can anyone give me some idea about how I can use the value of `wp_logout_url()` within the menu creator page of wordpress? As the menu creation page doesn't support php I cannot just put `echo wp_logout_url( home_url() )` under custom link.
Also I cannot use functions like
```
add_filter( 'wp_nav_menu_items', 'wti_loginout_menu_link', 10, 2 );
function wti_loginout_menu_link( $items, $args ) {
if ($args->theme_location == 'primary') {
if (is_user_logged_in()) {
$items .= '<li class="right"><a href="'. wp_logout_url() .'">Log Out</a></li>';
} else {
$items .= '<li class="right"><a href="'. wp_login_url(get_permalink()) .'">Log In</a></li>';
}
}
return $items;
}
```
because it doesn't fit my need, I have to add the logout link as a dropdown menu not as parent menu and also will show up in certain pages only. I can hel these things if anyone can show me the way how to fetch the `wp_logout_url()` data within the wp menu creation page.
Any help is highly appreciated.
|
Add submenu with a custom link, `/wp-login?action=logout`, like the image below:
[](https://i.stack.imgur.com/Aw4k3.png)
Add code like below in `functions.php`:
```
function wpa_remove_menu_item( $items, $menu, $args ) {
if ( is_admin() || ! is_user_logged_in() )
return $items;
foreach ( $items as $key => $item ) {
if ( 'Login / Register' == $item->title )
unset( $items[$key] );
if ( 'Logout' == $item->title ) {
$items[$key]->url = wp_logout_url();
}
}
return $items;
}
add_filter( 'wp_get_nav_menu_items', 'wpa_remove_menu_item', 10, 3 );
```
|
205,968 |
<p>IΒ΄m having some difficulty override to default category widgets in my wordpress theme. I created the theme from scratch.</p>
<p>I want to remove the <code><ul><li></li></ul></code> from categories in the lists. I want to add my own style using <code><a href=""></a></code> instead</p>
<pre><code><div class="list-group">
<a href="#" class="list-group-item">LifeStyle</a>
<a href="#" class="list-group-item">SmartPhones</a>
<a href="#" class="list-group-item">Business</a>
<a href="#" class="list-group-item">Graphic Design</a>
<a href="#" class="list-group-item">Agriculture</a>
<a href="#" class="list-group-item">Music</a>
<a href="#" class="list-group-item">Travel</a>
</code></pre>
<p></p>
<p>I can override it?</p>
|
[
{
"answer_id": 206108,
"author": "Hernan",
"author_id": 60187,
"author_profile": "https://wordpress.stackexchange.com/users/60187",
"pm_score": 2,
"selected": true,
"text": "<p>This is a really tricky and long question, there is no easy way to do this, as I guess you want to override this core WordPress function from within your theme.</p>\n\n<p>The way to go is a particular case of something <a href=\"https://wordpress.stackexchange.com/questions/33207/modify-a-output-of-a-widget\">explained here</a>, so you can do the following in your <code>functions.php</code>.</p>\n\n<p>Create a new class by copying the code from the <a href=\"https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-includes/default-widgets.php#L0\" rel=\"nofollow noreferrer\">original source</a>. Give it a new name (in this example I will be using <code>WP_Widget_Categories_Modified</code>), and start modifying it.</p>\n\n<p>After that you need to <em>unregister</em> the original Widget and <em>register</em> the new one (so, again, assuming your new class is named <code>WP_Widget_Categories_Modified</code>):</p>\n\n<pre><code>function replace_default_wp_widgets() {\n unregister_widget( 'WP_Widget_Categories' );\n register_widget( 'WP_Widget_Categories_Modified' );\n}\nadd_action( 'widgets_init', 'replace_default_wp_widgets', 1 );\n</code></pre>\n\n<p>Now, you have replaced the default class with the new one, which is exactly the same as the original. So you need to start modifying the new class you created.</p>\n\n<p>First of all, delete the <code><ul></code> and <code></ul></code> before and after <code>wp_list_categories</code> in your new Class (remember you copied the original code).</p>\n\n<p>Since the WordPress original class calls to <code>wp_list_categories</code>, which includes the code, the best choice is to add a custom 'walker' to the function.</p>\n\n<p>To do so, also add in your <code>functions.php</code> the walker, for instance:</p>\n\n<pre><code>class Walker_Categories_Plain extends Walker {\n var $db_fields = array( 'parent' => 'parent_id', 'id' => 'object_id' ); \n function start_el( &$output, $item, $depth = 0, $args = array() ) {\n $output .= \"\\n<a href='\" . get_term_link( $item ) . \"'>\" . $item->name . \"</a>\\n\";\n } \n}\n</code></pre>\n\n<p>Then, you need to pass this walker to <code>wp_list_categories</code>. To do this, add this argument as this, <strong>before</strong> the call to <code>wp_list_categories()</code>:</p>\n\n<pre><code>$cat_args['walker'] = new Walker_Categories_Plain;\n</code></pre>\n\n<p>That's it, it should work if I did not forget anything!</p>\n\n<p>The walker can be modified to change the output until you reach your desired code (check the <code>$output</code> string).</p>\n\n<p>Now, your theme:</p>\n\n<ol>\n<li>Hides the default Category Widget</li>\n<li>Registers its own Category Widget (which is only used to delete the <code><ul></code> and to pass the new Walker by default)</li>\n<li>Creates its custom Walker (may be used anywhere else to modify <code>wp_list_categories</code>)</li>\n</ol>\n"
},
{
"answer_id": 292153,
"author": "Sandeep",
"author_id": 135537,
"author_profile": "https://wordpress.stackexchange.com/users/135537",
"pm_score": 2,
"selected": false,
"text": "<p>This worked for me <code><?php echo the_category(' '); ?></code>.It removed ul li then you can style hyperlink using parent div class or id.</p>\n"
}
] |
2015/10/19
|
[
"https://wordpress.stackexchange.com/questions/205968",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80230/"
] |
IΒ΄m having some difficulty override to default category widgets in my wordpress theme. I created the theme from scratch.
I want to remove the `<ul><li></li></ul>` from categories in the lists. I want to add my own style using `<a href=""></a>` instead
```
<div class="list-group">
<a href="#" class="list-group-item">LifeStyle</a>
<a href="#" class="list-group-item">SmartPhones</a>
<a href="#" class="list-group-item">Business</a>
<a href="#" class="list-group-item">Graphic Design</a>
<a href="#" class="list-group-item">Agriculture</a>
<a href="#" class="list-group-item">Music</a>
<a href="#" class="list-group-item">Travel</a>
```
I can override it?
|
This is a really tricky and long question, there is no easy way to do this, as I guess you want to override this core WordPress function from within your theme.
The way to go is a particular case of something [explained here](https://wordpress.stackexchange.com/questions/33207/modify-a-output-of-a-widget), so you can do the following in your `functions.php`.
Create a new class by copying the code from the [original source](https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-includes/default-widgets.php#L0). Give it a new name (in this example I will be using `WP_Widget_Categories_Modified`), and start modifying it.
After that you need to *unregister* the original Widget and *register* the new one (so, again, assuming your new class is named `WP_Widget_Categories_Modified`):
```
function replace_default_wp_widgets() {
unregister_widget( 'WP_Widget_Categories' );
register_widget( 'WP_Widget_Categories_Modified' );
}
add_action( 'widgets_init', 'replace_default_wp_widgets', 1 );
```
Now, you have replaced the default class with the new one, which is exactly the same as the original. So you need to start modifying the new class you created.
First of all, delete the `<ul>` and `</ul>` before and after `wp_list_categories` in your new Class (remember you copied the original code).
Since the WordPress original class calls to `wp_list_categories`, which includes the code, the best choice is to add a custom 'walker' to the function.
To do so, also add in your `functions.php` the walker, for instance:
```
class Walker_Categories_Plain extends Walker {
var $db_fields = array( 'parent' => 'parent_id', 'id' => 'object_id' );
function start_el( &$output, $item, $depth = 0, $args = array() ) {
$output .= "\n<a href='" . get_term_link( $item ) . "'>" . $item->name . "</a>\n";
}
}
```
Then, you need to pass this walker to `wp_list_categories`. To do this, add this argument as this, **before** the call to `wp_list_categories()`:
```
$cat_args['walker'] = new Walker_Categories_Plain;
```
That's it, it should work if I did not forget anything!
The walker can be modified to change the output until you reach your desired code (check the `$output` string).
Now, your theme:
1. Hides the default Category Widget
2. Registers its own Category Widget (which is only used to delete the `<ul>` and to pass the new Walker by default)
3. Creates its custom Walker (may be used anywhere else to modify `wp_list_categories`)
|
205,975 |
<p>I have created a custom post type named <code>rooms</code>. I would like to get all <code>rooms</code> posts except for the one with the post id <code>164</code>, and display it using the code below: </p>
<pre><code><div class="room-container container room-grid">
<div class="heading-box">
<h2>rooms</h2>
</div>
<?php
$my_query = new WP_Query('post_type=rooms&posts_per_page=-1');
$c = 1;
while( $my_query->have_posts() ) :
$my_query->the_post();
$thumb = get_post_thumbnail_id();
$img_url = wp_get_attachment_url( $thumb );
$content = get_the_content();
?>
<div class="room-box col-xs-6">
<div class="img-container">
<img src="<?php echo $img_url; ?>" alt="rooms">
<a href="#" class="btn btn-default">More Details</a>
</div>
<div class="details">
<div class="title">
<a href="#"><?php echo get_the_title(); ?></a>
</div>
<div class="desc">
<?php echo substr( $content, 0, 200 ); ?>...
</div>
</div>
</div>
<?php $c++; endwhile; ?>
</div>
</code></pre>
|
[
{
"answer_id": 205976,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">WP_Query</a> has a <strong><em>ton</em></strong> of indices you can define. The one you need is <code>posts__not_in</code> under <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters\" rel=\"nofollow\">Post and Page Parameters</a> section. It would look like this in practice:</p>\n\n<pre><code>$my_query = new WP_Query( array(\n 'post_type' => 'rooms',\n 'posts_per_page' => -1,\n 'posts__not_in' => array( 164 ),\n) ); \n</code></pre>\n\n<p>This will get all posts in the <code>rooms</code> post type with the exception of <code>post_id</code> 164.</p>\n"
},
{
"answer_id": 205978,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 2,
"selected": false,
"text": "<p>Use the <code>post__not_in</code> Argument of wp_query like this</p>\n\n<pre><code>$query= new WP_Query(array('post_type' => 'rooms', 'post__not_in' => array(164));\n</code></pre>\n"
},
{
"answer_id": 206180,
"author": "codieboie",
"author_id": 77627,
"author_profile": "https://wordpress.stackexchange.com/users/77627",
"pm_score": 1,
"selected": true,
"text": "<p>I got the working code. rooms doesnt need 'rooms'. Thankyou friends.. </p>\n\n<pre><code><?php\n $my_query = new WP_Query( array('post_type' => rooms, 'post__not_in' => array(164)) );\n while ($my_query->have_posts()) : $my_query->the_post(); \n $thumb = get_post_thumbnail_id(); \n $img_url = wp_get_attachment_url( $thumb);\n $content = get_the_content();\n ?>\n</code></pre>\n"
}
] |
2015/10/19
|
[
"https://wordpress.stackexchange.com/questions/205975",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77627/"
] |
I have created a custom post type named `rooms`. I would like to get all `rooms` posts except for the one with the post id `164`, and display it using the code below:
```
<div class="room-container container room-grid">
<div class="heading-box">
<h2>rooms</h2>
</div>
<?php
$my_query = new WP_Query('post_type=rooms&posts_per_page=-1');
$c = 1;
while( $my_query->have_posts() ) :
$my_query->the_post();
$thumb = get_post_thumbnail_id();
$img_url = wp_get_attachment_url( $thumb );
$content = get_the_content();
?>
<div class="room-box col-xs-6">
<div class="img-container">
<img src="<?php echo $img_url; ?>" alt="rooms">
<a href="#" class="btn btn-default">More Details</a>
</div>
<div class="details">
<div class="title">
<a href="#"><?php echo get_the_title(); ?></a>
</div>
<div class="desc">
<?php echo substr( $content, 0, 200 ); ?>...
</div>
</div>
</div>
<?php $c++; endwhile; ?>
</div>
```
|
I got the working code. rooms doesnt need 'rooms'. Thankyou friends..
```
<?php
$my_query = new WP_Query( array('post_type' => rooms, 'post__not_in' => array(164)) );
while ($my_query->have_posts()) : $my_query->the_post();
$thumb = get_post_thumbnail_id();
$img_url = wp_get_attachment_url( $thumb);
$content = get_the_content();
?>
```
|
205,989 |
<p>As you can see in the post title at <a href="http://fosit.staging.wpengine.com/" rel="nofollow">http://fosit.staging.wpengine.com/</a>, when the post title gets to the margin it doesn't continue on a new line; it continues on the <em>same</em> line.</p>
<p>I don't know if this problem is native to twenty twelve or if it's due a change I made to the child theme (like when I moved the date of the post from after the post to under the title).</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 205991,
"author": "Gyanendra Giri",
"author_id": 47270,
"author_profile": "https://wordpress.stackexchange.com/users/47270",
"pm_score": 1,
"selected": false,
"text": "<p>The issue is due to addition of following line in your child theme. There should be some line height to show header properly.</p>\n\n<pre><code>.entry-header .entry-title {\n font-size: 1.6000rem; /* was 1.42857rem; */\n font-weight: normal;\n line-height: 0; /* changed from 1.2 */ \n}\n</code></pre>\n"
},
{
"answer_id": 206001,
"author": "Nikhil",
"author_id": 26760,
"author_profile": "https://wordpress.stackexchange.com/users/26760",
"pm_score": 0,
"selected": false,
"text": "<p>Please add the following css to your style-sheet (style.css). </p>\n\n<pre><code>.entry-header .entry-title{\n display: inline !important;\n line-height: 1 !important;\n}\n</code></pre>\n\n<p>I've tested this by inspecting the website and it is working.</p>\n"
},
{
"answer_id": 206006,
"author": "Ashok Dhaduk",
"author_id": 81215,
"author_profile": "https://wordpress.stackexchange.com/users/81215",
"pm_score": 0,
"selected": false,
"text": "<p>you just needs to remove line-height then your issue will be fixed.</p>\n\n<p><a href=\"https://i.stack.imgur.com/fWL7o.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fWL7o.png\" alt=\"enter image description here\"></a></p>\n"
}
] |
2015/10/20
|
[
"https://wordpress.stackexchange.com/questions/205989",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81348/"
] |
As you can see in the post title at <http://fosit.staging.wpengine.com/>, when the post title gets to the margin it doesn't continue on a new line; it continues on the *same* line.
I don't know if this problem is native to twenty twelve or if it's due a change I made to the child theme (like when I moved the date of the post from after the post to under the title).
Any ideas?
|
The issue is due to addition of following line in your child theme. There should be some line height to show header properly.
```
.entry-header .entry-title {
font-size: 1.6000rem; /* was 1.42857rem; */
font-weight: normal;
line-height: 0; /* changed from 1.2 */
}
```
|
205,992 |
<p>I have a custom page template and I want it to display on specific pages. The only way I know to do this is to create a shortcode for this custom page template, so that I can use the custom page template by using shortcode. But I don't know how doing this.</p>
<p>I saw some article about this, but I forgot the website link.</p>
<p>How to create a shortcode for custom page template?</p>
|
[
{
"answer_id": 205993,
"author": "user3818821",
"author_id": 81799,
"author_profile": "https://wordpress.stackexchange.com/users/81799",
"pm_score": 3,
"selected": false,
"text": "<p>I solved now, by adding this snippet in <code>functions.php</code></p>\n\n<pre><code>function my_form_shortcode() {\n ob_start();\n get_template_part('my_form_template');\n return ob_get_clean(); \n} \nadd_shortcode( 'my_form_shortcode', 'my_form_shortcode' );\n</code></pre>\n"
},
{
"answer_id": 295450,
"author": "user2652061",
"author_id": 137711,
"author_profile": "https://wordpress.stackexchange.com/users/137711",
"pm_score": 1,
"selected": false,
"text": "<p>I solved using below method.</p>\n\n<p>Using Plugin (<strong>Shortcodes Ultimate</strong>) we can create or make shortcode for wordpress custom page template.</p>\n\n<ol>\n<li>create your custom page template without including header and footer.</li>\n<li>Install the plugin(<strong>find link below</strong>) into wordpress site.</li>\n<li>Activate it.</li>\n<li>Go to plugin <strong>Shortcodes Ultimate βΊ Available shortcodes</strong>.</li>\n<li>You can find the variety of filter options in that click <strong>Other</strong> will find <strong>Template</strong> open that.</li>\n<li>In shortcode section add the name of your custom template(<strong>[su_template name=\"name-of-your-template.php\"]</strong>) with or without php extentions.</li>\n<li>Use template file name (with optional .php extension). If you need to use templates from theme sub-folder, use relative path. Example values: page, page.php, includes/page.php</li>\n<li>Now copy the whole shortcode and paste it into the page or post you want.</li>\n</ol>\n\n<p>Plugin download link</p>\n\n<p><a href=\"http://wordpress.org/plugins/shortcodes-ultimate/\" rel=\"nofollow noreferrer\">Shortcodes Ultimate</a></p>\n"
},
{
"answer_id": 372151,
"author": "Niru",
"author_id": 192499,
"author_profile": "https://wordpress.stackexchange.com/users/192499",
"pm_score": 1,
"selected": false,
"text": "<p>I find <a href=\"https://css-tricks.com/snippets/wordpress/shortcode-in-a-template/\" rel=\"nofollow noreferrer\">this</a> one is the easiest way:</p>\n<pre><code><?php echo do_shortcode("[shortcode]"); ?>\n</code></pre>\n"
}
] |
2015/10/20
|
[
"https://wordpress.stackexchange.com/questions/205992",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81799/"
] |
I have a custom page template and I want it to display on specific pages. The only way I know to do this is to create a shortcode for this custom page template, so that I can use the custom page template by using shortcode. But I don't know how doing this.
I saw some article about this, but I forgot the website link.
How to create a shortcode for custom page template?
|
I solved now, by adding this snippet in `functions.php`
```
function my_form_shortcode() {
ob_start();
get_template_part('my_form_template');
return ob_get_clean();
}
add_shortcode( 'my_form_shortcode', 'my_form_shortcode' );
```
|
205,999 |
<p>I am trying to setup wordpress development environment for freelancers. I have freelancers working on my site from different locations. Which tools and technologies will support development of my current website and how?</p>
<p>I came across vagrant, will it be useful? Also, how can I do version control?</p>
<p>I have decided to go with sub-domain development environment, as I am not expecting my freelancers to install whole website on local. Our website is too big with multisite setup, we have three teams at different location, one for design and other two for development. Also we are expanding our team now and then. So installing on local would not be suitable. I am going to use git and bitbucket. Can I create my master git repository directly from sub-domain development environment? How git setup would be ideally? Where should be my master repository and how many branches I should create?</p>
|
[
{
"answer_id": 205993,
"author": "user3818821",
"author_id": 81799,
"author_profile": "https://wordpress.stackexchange.com/users/81799",
"pm_score": 3,
"selected": false,
"text": "<p>I solved now, by adding this snippet in <code>functions.php</code></p>\n\n<pre><code>function my_form_shortcode() {\n ob_start();\n get_template_part('my_form_template');\n return ob_get_clean(); \n} \nadd_shortcode( 'my_form_shortcode', 'my_form_shortcode' );\n</code></pre>\n"
},
{
"answer_id": 295450,
"author": "user2652061",
"author_id": 137711,
"author_profile": "https://wordpress.stackexchange.com/users/137711",
"pm_score": 1,
"selected": false,
"text": "<p>I solved using below method.</p>\n\n<p>Using Plugin (<strong>Shortcodes Ultimate</strong>) we can create or make shortcode for wordpress custom page template.</p>\n\n<ol>\n<li>create your custom page template without including header and footer.</li>\n<li>Install the plugin(<strong>find link below</strong>) into wordpress site.</li>\n<li>Activate it.</li>\n<li>Go to plugin <strong>Shortcodes Ultimate βΊ Available shortcodes</strong>.</li>\n<li>You can find the variety of filter options in that click <strong>Other</strong> will find <strong>Template</strong> open that.</li>\n<li>In shortcode section add the name of your custom template(<strong>[su_template name=\"name-of-your-template.php\"]</strong>) with or without php extentions.</li>\n<li>Use template file name (with optional .php extension). If you need to use templates from theme sub-folder, use relative path. Example values: page, page.php, includes/page.php</li>\n<li>Now copy the whole shortcode and paste it into the page or post you want.</li>\n</ol>\n\n<p>Plugin download link</p>\n\n<p><a href=\"http://wordpress.org/plugins/shortcodes-ultimate/\" rel=\"nofollow noreferrer\">Shortcodes Ultimate</a></p>\n"
},
{
"answer_id": 372151,
"author": "Niru",
"author_id": 192499,
"author_profile": "https://wordpress.stackexchange.com/users/192499",
"pm_score": 1,
"selected": false,
"text": "<p>I find <a href=\"https://css-tricks.com/snippets/wordpress/shortcode-in-a-template/\" rel=\"nofollow noreferrer\">this</a> one is the easiest way:</p>\n<pre><code><?php echo do_shortcode("[shortcode]"); ?>\n</code></pre>\n"
}
] |
2015/10/20
|
[
"https://wordpress.stackexchange.com/questions/205999",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82206/"
] |
I am trying to setup wordpress development environment for freelancers. I have freelancers working on my site from different locations. Which tools and technologies will support development of my current website and how?
I came across vagrant, will it be useful? Also, how can I do version control?
I have decided to go with sub-domain development environment, as I am not expecting my freelancers to install whole website on local. Our website is too big with multisite setup, we have three teams at different location, one for design and other two for development. Also we are expanding our team now and then. So installing on local would not be suitable. I am going to use git and bitbucket. Can I create my master git repository directly from sub-domain development environment? How git setup would be ideally? Where should be my master repository and how many branches I should create?
|
I solved now, by adding this snippet in `functions.php`
```
function my_form_shortcode() {
ob_start();
get_template_part('my_form_template');
return ob_get_clean();
}
add_shortcode( 'my_form_shortcode', 'my_form_shortcode' );
```
|
206,021 |
<p>I am new to custom fields thing. I am working on a movie review site. And wants to add movie story or plot field, I have successfully added the custom field named Story and its content is displaying on single.php. However, can I display same on index.php? Below is my code.</p>
<pre><code><?php
$meta = get_post_meta( get_the_ID(), 'Story' );
if( !empty($meta) ) {
echo $meta[0];
}?>
</code></pre>
|
[
{
"answer_id": 206024,
"author": "Ravi Patel",
"author_id": 35477,
"author_profile": "https://wordpress.stackexchange.com/users/35477",
"pm_score": 0,
"selected": false,
"text": "<p>Add this code on content.php because of index.php content comes from this file.</p>\n\n<pre><code>if u call outside of post use \nglobal $post; \n$meta = get_post_meta($post->ID , 'Story', true);\n\nOR inner loop\n\n$meta = get_post_meta(get_the_id(), 'Story', true);\n\nif( !empty($meta) ) {\n echo $meta[0];\n}\n</code></pre>\n"
},
{
"answer_id": 206040,
"author": "Ivijan Stefan StipiΔ",
"author_id": 82023,
"author_profile": "https://wordpress.stackexchange.com/users/82023",
"pm_score": 1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>if ( ! function_exists( 'customField' ) ) :\nfunction customField($name, $id=false, $single=false){\n global $post_type, $post;\n\n $name=trim($name);\n $prefix=''; // only if you need this\n $data=NULL;\n\n if($id!==false && !empty($id) && $id > 0)\n $getMeta=get_post_meta((int)$id, $prefix.$name, $single);\n else if(isset($post->ID) && $post->ID > 0)\n $getMeta=get_post_meta($post->ID,$prefix.$name, $single);\n else if('page' == get_option( 'show_on_front' ))\n $getMeta=get_post_meta(get_option( 'page_for_posts' ),$prefix.$name, $single);\n else if(is_home() || is_front_page() || get_queried_object_id() > 0)\n $getMeta=get_post_meta(get_queried_object_id(),$prefix.$name, $single);\n else\n $getMeta=get_post_meta(get_the_id(),$prefix.$name, $single);\n\n if(isset($getMeta[0])) $data=$getMeta[0];\n\n if($data===false || !is_numeric($data) && (empty($data) || is_null($data))) return NULL;\n\n $return = preg_replace(array('%<p>(<img .*?/>)</p>%i','%<p>&nbsp;</p>%i','/^\\s*(?:<br\\s*\\/?>\\s*)*/i'), array('$1','',''),$data);\n\n return (!empty($return)?$return:NULL);\n}\nendif;\n\n\necho customField(\"story\"); // Default\necho customField(\"story\", 55); // With custom page ID\n</code></pre>\n\n<p>This code work great becouse I build this for my works. If return empty, in place where you setup pharameters, you not save your data. Also be careful about prefix of your metabox if you use it.</p>\n"
}
] |
2015/10/20
|
[
"https://wordpress.stackexchange.com/questions/206021",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38763/"
] |
I am new to custom fields thing. I am working on a movie review site. And wants to add movie story or plot field, I have successfully added the custom field named Story and its content is displaying on single.php. However, can I display same on index.php? Below is my code.
```
<?php
$meta = get_post_meta( get_the_ID(), 'Story' );
if( !empty($meta) ) {
echo $meta[0];
}?>
```
|
Try this:
```
if ( ! function_exists( 'customField' ) ) :
function customField($name, $id=false, $single=false){
global $post_type, $post;
$name=trim($name);
$prefix=''; // only if you need this
$data=NULL;
if($id!==false && !empty($id) && $id > 0)
$getMeta=get_post_meta((int)$id, $prefix.$name, $single);
else if(isset($post->ID) && $post->ID > 0)
$getMeta=get_post_meta($post->ID,$prefix.$name, $single);
else if('page' == get_option( 'show_on_front' ))
$getMeta=get_post_meta(get_option( 'page_for_posts' ),$prefix.$name, $single);
else if(is_home() || is_front_page() || get_queried_object_id() > 0)
$getMeta=get_post_meta(get_queried_object_id(),$prefix.$name, $single);
else
$getMeta=get_post_meta(get_the_id(),$prefix.$name, $single);
if(isset($getMeta[0])) $data=$getMeta[0];
if($data===false || !is_numeric($data) && (empty($data) || is_null($data))) return NULL;
$return = preg_replace(array('%<p>(<img .*?/>)</p>%i','%<p> </p>%i','/^\s*(?:<br\s*\/?>\s*)*/i'), array('$1','',''),$data);
return (!empty($return)?$return:NULL);
}
endif;
echo customField("story"); // Default
echo customField("story", 55); // With custom page ID
```
This code work great becouse I build this for my works. If return empty, in place where you setup pharameters, you not save your data. Also be careful about prefix of your metabox if you use it.
|
206,022 |
<p>I have tried to update my plugins in wordpress-admin but for some reason i am receiving an error "Unable to locate WordPress Content directory (wp-content)" I have checked on my server and the folder still exists. What is this cause of this and is there a quick fix?</p>
|
[
{
"answer_id": 206023,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 2,
"selected": false,
"text": "<p>Adding below code to <code>wp-config.php</code> file will solve your problem:</p>\n\n<pre><code>if(is_admin()) {\n add_filter('filesystem_method', create_function('$a', 'return \"direct\";' ));\n define( 'FS_CHMOD_DIR', 0751 );\n}\n</code></pre>\n\n<p>Above is quick fix I found on Wordpress support but problem is with permissions.</p>\n\n<p><a href=\"https://wordpress.org/support/topic/unable-to-locate-wordpress-content-directory-wp-content?replies=15\" rel=\"nofollow noreferrer\">For details please follow link</a></p>\n\n<p>Please check you permissions: </p>\n\n<p>All FILES should have permissions set to 644</p>\n\n<p>All DIRECTORIES (i.e. folders) should have permissions set to 755</p>\n\n<p><a href=\"https://stackoverflow.com/questions/18352682/correct-file-permissions-for-wordpress\">For Correct file Permissions</a></p>\n\n<p>Thanks!</p>\n"
},
{
"answer_id": 264895,
"author": "Rocky",
"author_id": 118421,
"author_profile": "https://wordpress.stackexchange.com/users/118421",
"pm_score": 0,
"selected": false,
"text": "<p>Also had this error and it was because of server FTP and NAT configuration and I was updating WordPress via FTP. Changing the WP update page to use the IP address of the web server instead of the domain name of the web site solved the problem.</p>\n"
},
{
"answer_id": 296373,
"author": "thefid",
"author_id": 138345,
"author_profile": "https://wordpress.stackexchange.com/users/138345",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using IIS to host your site, open the file explorer on the server and right click on your website (WordPress) folder. Select Properties --> Security and edit the \"USERS\" permissions to enable Read, Write, List, and Modify privileges. </p>\n\n<p>Doing this also fixed my issue with importing content data.</p>\n"
},
{
"answer_id": 317155,
"author": "Ibrahim.H",
"author_id": 152673,
"author_profile": "https://wordpress.stackexchange.com/users/152673",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same issue, this is usually a permission of writing in specific folder, in my case I had to change the owner of the <code>uploads/</code> directory, here is what I did in <code>wp-content</code> directory:</p>\n\n<pre><code>sudo chown -R daemon uploads/\n</code></pre>\n\n<p>where the user <code>daemon</code> is the owner of the process <code>httpd</code>.</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 411694,
"author": "Vlad",
"author_id": 227948,
"author_profile": "https://wordpress.stackexchange.com/users/227948",
"pm_score": -1,
"selected": false,
"text": "<p>I found the solution at the following link: <a href=\"https://www.youtube.com/watch?v=Ymc1CBdbsJ8\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=Ymc1CBdbsJ8</a></p>\n"
}
] |
2015/10/20
|
[
"https://wordpress.stackexchange.com/questions/206022",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82219/"
] |
I have tried to update my plugins in wordpress-admin but for some reason i am receiving an error "Unable to locate WordPress Content directory (wp-content)" I have checked on my server and the folder still exists. What is this cause of this and is there a quick fix?
|
Adding below code to `wp-config.php` file will solve your problem:
```
if(is_admin()) {
add_filter('filesystem_method', create_function('$a', 'return "direct";' ));
define( 'FS_CHMOD_DIR', 0751 );
}
```
Above is quick fix I found on Wordpress support but problem is with permissions.
[For details please follow link](https://wordpress.org/support/topic/unable-to-locate-wordpress-content-directory-wp-content?replies=15)
Please check you permissions:
All FILES should have permissions set to 644
All DIRECTORIES (i.e. folders) should have permissions set to 755
[For Correct file Permissions](https://stackoverflow.com/questions/18352682/correct-file-permissions-for-wordpress)
Thanks!
|
206,030 |
<p>I'm trying to interpret this action hook name: </p>
<pre><code>ws_plugin__s2member_pro_before_sc_authnet_form_after_shortcode_atts
</code></pre>
<p>What is meaning of BEFORE and AFTER in this hook name? Do the underscores mean anything? </p>
<p>It seems that the hook name contains two function names, <code>sc_authnet_form</code> and <code>shortcode_atts</code>, that are connected by BEFORE and AFTER words. </p>
|
[
{
"answer_id": 206023,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 2,
"selected": false,
"text": "<p>Adding below code to <code>wp-config.php</code> file will solve your problem:</p>\n\n<pre><code>if(is_admin()) {\n add_filter('filesystem_method', create_function('$a', 'return \"direct\";' ));\n define( 'FS_CHMOD_DIR', 0751 );\n}\n</code></pre>\n\n<p>Above is quick fix I found on Wordpress support but problem is with permissions.</p>\n\n<p><a href=\"https://wordpress.org/support/topic/unable-to-locate-wordpress-content-directory-wp-content?replies=15\" rel=\"nofollow noreferrer\">For details please follow link</a></p>\n\n<p>Please check you permissions: </p>\n\n<p>All FILES should have permissions set to 644</p>\n\n<p>All DIRECTORIES (i.e. folders) should have permissions set to 755</p>\n\n<p><a href=\"https://stackoverflow.com/questions/18352682/correct-file-permissions-for-wordpress\">For Correct file Permissions</a></p>\n\n<p>Thanks!</p>\n"
},
{
"answer_id": 264895,
"author": "Rocky",
"author_id": 118421,
"author_profile": "https://wordpress.stackexchange.com/users/118421",
"pm_score": 0,
"selected": false,
"text": "<p>Also had this error and it was because of server FTP and NAT configuration and I was updating WordPress via FTP. Changing the WP update page to use the IP address of the web server instead of the domain name of the web site solved the problem.</p>\n"
},
{
"answer_id": 296373,
"author": "thefid",
"author_id": 138345,
"author_profile": "https://wordpress.stackexchange.com/users/138345",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using IIS to host your site, open the file explorer on the server and right click on your website (WordPress) folder. Select Properties --> Security and edit the \"USERS\" permissions to enable Read, Write, List, and Modify privileges. </p>\n\n<p>Doing this also fixed my issue with importing content data.</p>\n"
},
{
"answer_id": 317155,
"author": "Ibrahim.H",
"author_id": 152673,
"author_profile": "https://wordpress.stackexchange.com/users/152673",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same issue, this is usually a permission of writing in specific folder, in my case I had to change the owner of the <code>uploads/</code> directory, here is what I did in <code>wp-content</code> directory:</p>\n\n<pre><code>sudo chown -R daemon uploads/\n</code></pre>\n\n<p>where the user <code>daemon</code> is the owner of the process <code>httpd</code>.</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 411694,
"author": "Vlad",
"author_id": 227948,
"author_profile": "https://wordpress.stackexchange.com/users/227948",
"pm_score": -1,
"selected": false,
"text": "<p>I found the solution at the following link: <a href=\"https://www.youtube.com/watch?v=Ymc1CBdbsJ8\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=Ymc1CBdbsJ8</a></p>\n"
}
] |
2015/10/20
|
[
"https://wordpress.stackexchange.com/questions/206030",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82226/"
] |
I'm trying to interpret this action hook name:
```
ws_plugin__s2member_pro_before_sc_authnet_form_after_shortcode_atts
```
What is meaning of BEFORE and AFTER in this hook name? Do the underscores mean anything?
It seems that the hook name contains two function names, `sc_authnet_form` and `shortcode_atts`, that are connected by BEFORE and AFTER words.
|
Adding below code to `wp-config.php` file will solve your problem:
```
if(is_admin()) {
add_filter('filesystem_method', create_function('$a', 'return "direct";' ));
define( 'FS_CHMOD_DIR', 0751 );
}
```
Above is quick fix I found on Wordpress support but problem is with permissions.
[For details please follow link](https://wordpress.org/support/topic/unable-to-locate-wordpress-content-directory-wp-content?replies=15)
Please check you permissions:
All FILES should have permissions set to 644
All DIRECTORIES (i.e. folders) should have permissions set to 755
[For Correct file Permissions](https://stackoverflow.com/questions/18352682/correct-file-permissions-for-wordpress)
Thanks!
|
206,054 |
<p>I am trying to hide a specific post from a page template? Does anyone have experience with this, would prefer to not have to use a plugin. Was thinking of using wp_post ID but am unsure of how to go about it.</p>
|
[
{
"answer_id": 206023,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 2,
"selected": false,
"text": "<p>Adding below code to <code>wp-config.php</code> file will solve your problem:</p>\n\n<pre><code>if(is_admin()) {\n add_filter('filesystem_method', create_function('$a', 'return \"direct\";' ));\n define( 'FS_CHMOD_DIR', 0751 );\n}\n</code></pre>\n\n<p>Above is quick fix I found on Wordpress support but problem is with permissions.</p>\n\n<p><a href=\"https://wordpress.org/support/topic/unable-to-locate-wordpress-content-directory-wp-content?replies=15\" rel=\"nofollow noreferrer\">For details please follow link</a></p>\n\n<p>Please check you permissions: </p>\n\n<p>All FILES should have permissions set to 644</p>\n\n<p>All DIRECTORIES (i.e. folders) should have permissions set to 755</p>\n\n<p><a href=\"https://stackoverflow.com/questions/18352682/correct-file-permissions-for-wordpress\">For Correct file Permissions</a></p>\n\n<p>Thanks!</p>\n"
},
{
"answer_id": 264895,
"author": "Rocky",
"author_id": 118421,
"author_profile": "https://wordpress.stackexchange.com/users/118421",
"pm_score": 0,
"selected": false,
"text": "<p>Also had this error and it was because of server FTP and NAT configuration and I was updating WordPress via FTP. Changing the WP update page to use the IP address of the web server instead of the domain name of the web site solved the problem.</p>\n"
},
{
"answer_id": 296373,
"author": "thefid",
"author_id": 138345,
"author_profile": "https://wordpress.stackexchange.com/users/138345",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using IIS to host your site, open the file explorer on the server and right click on your website (WordPress) folder. Select Properties --> Security and edit the \"USERS\" permissions to enable Read, Write, List, and Modify privileges. </p>\n\n<p>Doing this also fixed my issue with importing content data.</p>\n"
},
{
"answer_id": 317155,
"author": "Ibrahim.H",
"author_id": 152673,
"author_profile": "https://wordpress.stackexchange.com/users/152673",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same issue, this is usually a permission of writing in specific folder, in my case I had to change the owner of the <code>uploads/</code> directory, here is what I did in <code>wp-content</code> directory:</p>\n\n<pre><code>sudo chown -R daemon uploads/\n</code></pre>\n\n<p>where the user <code>daemon</code> is the owner of the process <code>httpd</code>.</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 411694,
"author": "Vlad",
"author_id": 227948,
"author_profile": "https://wordpress.stackexchange.com/users/227948",
"pm_score": -1,
"selected": false,
"text": "<p>I found the solution at the following link: <a href=\"https://www.youtube.com/watch?v=Ymc1CBdbsJ8\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=Ymc1CBdbsJ8</a></p>\n"
}
] |
2015/10/20
|
[
"https://wordpress.stackexchange.com/questions/206054",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71177/"
] |
I am trying to hide a specific post from a page template? Does anyone have experience with this, would prefer to not have to use a plugin. Was thinking of using wp\_post ID but am unsure of how to go about it.
|
Adding below code to `wp-config.php` file will solve your problem:
```
if(is_admin()) {
add_filter('filesystem_method', create_function('$a', 'return "direct";' ));
define( 'FS_CHMOD_DIR', 0751 );
}
```
Above is quick fix I found on Wordpress support but problem is with permissions.
[For details please follow link](https://wordpress.org/support/topic/unable-to-locate-wordpress-content-directory-wp-content?replies=15)
Please check you permissions:
All FILES should have permissions set to 644
All DIRECTORIES (i.e. folders) should have permissions set to 755
[For Correct file Permissions](https://stackoverflow.com/questions/18352682/correct-file-permissions-for-wordpress)
Thanks!
|
206,057 |
<p>I'm currently working with an XML feed to add posts to a custom post type using wp_insert_post().</p>
<p>It's all working fine but I was wondering if there's a way I can check if the post exists and amend any meta values in the post. The posts do have a unique ID associated to them if that helps. This is not a WordPress ID but a unique seven digit one.</p>
<p>So basically, is there a way to check against existing posts, update the information in them and add new posts if they don't yet exist?</p>
|
[
{
"answer_id": 206023,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 2,
"selected": false,
"text": "<p>Adding below code to <code>wp-config.php</code> file will solve your problem:</p>\n\n<pre><code>if(is_admin()) {\n add_filter('filesystem_method', create_function('$a', 'return \"direct\";' ));\n define( 'FS_CHMOD_DIR', 0751 );\n}\n</code></pre>\n\n<p>Above is quick fix I found on Wordpress support but problem is with permissions.</p>\n\n<p><a href=\"https://wordpress.org/support/topic/unable-to-locate-wordpress-content-directory-wp-content?replies=15\" rel=\"nofollow noreferrer\">For details please follow link</a></p>\n\n<p>Please check you permissions: </p>\n\n<p>All FILES should have permissions set to 644</p>\n\n<p>All DIRECTORIES (i.e. folders) should have permissions set to 755</p>\n\n<p><a href=\"https://stackoverflow.com/questions/18352682/correct-file-permissions-for-wordpress\">For Correct file Permissions</a></p>\n\n<p>Thanks!</p>\n"
},
{
"answer_id": 264895,
"author": "Rocky",
"author_id": 118421,
"author_profile": "https://wordpress.stackexchange.com/users/118421",
"pm_score": 0,
"selected": false,
"text": "<p>Also had this error and it was because of server FTP and NAT configuration and I was updating WordPress via FTP. Changing the WP update page to use the IP address of the web server instead of the domain name of the web site solved the problem.</p>\n"
},
{
"answer_id": 296373,
"author": "thefid",
"author_id": 138345,
"author_profile": "https://wordpress.stackexchange.com/users/138345",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using IIS to host your site, open the file explorer on the server and right click on your website (WordPress) folder. Select Properties --> Security and edit the \"USERS\" permissions to enable Read, Write, List, and Modify privileges. </p>\n\n<p>Doing this also fixed my issue with importing content data.</p>\n"
},
{
"answer_id": 317155,
"author": "Ibrahim.H",
"author_id": 152673,
"author_profile": "https://wordpress.stackexchange.com/users/152673",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same issue, this is usually a permission of writing in specific folder, in my case I had to change the owner of the <code>uploads/</code> directory, here is what I did in <code>wp-content</code> directory:</p>\n\n<pre><code>sudo chown -R daemon uploads/\n</code></pre>\n\n<p>where the user <code>daemon</code> is the owner of the process <code>httpd</code>.</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 411694,
"author": "Vlad",
"author_id": 227948,
"author_profile": "https://wordpress.stackexchange.com/users/227948",
"pm_score": -1,
"selected": false,
"text": "<p>I found the solution at the following link: <a href=\"https://www.youtube.com/watch?v=Ymc1CBdbsJ8\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=Ymc1CBdbsJ8</a></p>\n"
}
] |
2015/10/20
|
[
"https://wordpress.stackexchange.com/questions/206057",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66977/"
] |
I'm currently working with an XML feed to add posts to a custom post type using wp\_insert\_post().
It's all working fine but I was wondering if there's a way I can check if the post exists and amend any meta values in the post. The posts do have a unique ID associated to them if that helps. This is not a WordPress ID but a unique seven digit one.
So basically, is there a way to check against existing posts, update the information in them and add new posts if they don't yet exist?
|
Adding below code to `wp-config.php` file will solve your problem:
```
if(is_admin()) {
add_filter('filesystem_method', create_function('$a', 'return "direct";' ));
define( 'FS_CHMOD_DIR', 0751 );
}
```
Above is quick fix I found on Wordpress support but problem is with permissions.
[For details please follow link](https://wordpress.org/support/topic/unable-to-locate-wordpress-content-directory-wp-content?replies=15)
Please check you permissions:
All FILES should have permissions set to 644
All DIRECTORIES (i.e. folders) should have permissions set to 755
[For Correct file Permissions](https://stackoverflow.com/questions/18352682/correct-file-permissions-for-wordpress)
Thanks!
|
206,069 |
<p>How would I go about writing an intersect query (using WP Query) that returns a set of posts that are in both category A and category B? </p>
|
[
{
"answer_id": 206070,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 0,
"selected": false,
"text": "<p>You just need a <code>tax_query</code> with the <code>AND</code> relation. <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">For example, this one cribbed from the Codex, with one change</a>:</p>\n\n<pre><code> 'tax_query' => array(\n 'relation' => 'AND', // here is the change\n array(\n 'taxonomy' => 'category',\n 'field' => 'slug',\n 'terms' => array( 'quotes' ),\n ),\n array(\n 'taxonomy' => 'post_format',\n 'field' => 'slug',\n 'terms' => array( 'post-format-quote' ),\n ),\n ),\n</code></pre>\n"
},
{
"answer_id": 206072,
"author": "BA_Webimax",
"author_id": 44566,
"author_profile": "https://wordpress.stackexchange.com/users/44566",
"pm_score": 2,
"selected": true,
"text": "<p>There is a simple way using a default argument...</p>\n\n<pre><code>/*\n* You need to get the IDs for the Categories you wish to include\n*/\n$args = array(\n 'category__and' => array( 1, 3 )\n);\n\n$the_query = new WP_Query( $args );\n\nif ( $the_query->have_posts() ) \n{\n // Do something to display your posts\n ...\n} else \n{\n // no posts\n}\n\nwp_reset_postdata();\n</code></pre>\n"
}
] |
2015/10/20
|
[
"https://wordpress.stackexchange.com/questions/206069",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75166/"
] |
How would I go about writing an intersect query (using WP Query) that returns a set of posts that are in both category A and category B?
|
There is a simple way using a default argument...
```
/*
* You need to get the IDs for the Categories you wish to include
*/
$args = array(
'category__and' => array( 1, 3 )
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() )
{
// Do something to display your posts
...
} else
{
// no posts
}
wp_reset_postdata();
```
|
206,083 |
<p>I'm trying to create a category template in my theme that will display static content if the user is on the first page of the archive, and then display the posts in the category on the following pages. I'm basically trying to replicate the category behavior on Wired.com where <a href="http://www.wired.com/category/design">http://www.wired.com/category/design</a> is a landing page while /category/design/page/1 shows a reverse chronological listing of posts like you would expect on a category archive.</p>
<p>The key here is that I'm not showing any posts from the category archive on the first page, so I need the next page to start with the first post. I first tried doing this using <a href="https://codex.wordpress.org/Making_Custom_Queries_using_Offset_and_Pagination">offset and manual pagination</a> by setting the offset of the query to 0 if the 'paged' query var was 2. But offset is ignored when it's set to zero, so the best I can do is set the offset to 1 and start with the second post in the category.</p>
<p>This is what I added to functions.php:</p>
<pre><code>add_action('pre_get_posts', 'category_query_offset', 1 );
function category_query_offset(&$query) {
// Before anything else, make sure this is the right query
if (!$query->is_category('news')) {
return;
}
// Next, determine how many posts per page
$ppp = get_option('posts_per_page');
//Next, detect and handle pagination
if ($query->is_paged) {
// Manually determine page query offset
$page_offset = (($query->query_vars['paged']-1) * $ppp) - $ppp;
// Apply adjust page offset
$query->set('offset', $page_offset );
}
}
</code></pre>
<p>What would be better, and what it appears <em>Wired</em> does, is to use the default pagination so the posts start on page 1, but insert a page 0 for the static content. Hypothetically, this seems like it would be possible by displaying the static content if 'paged' is 0, and displaying the first page of posts if 'paged' is 1. The problem is that 'paged' is never 1 because Wordpress sets 'paged' to zero when the user requests the first page. That means 'paged' is 0 for both /category/news/page/1 and /category/news.</p>
<p>Is there a way to check if the user requested /category/news/page/1 as opposed to /category/news? Failing that, is there a way to display all the posts in the category starting on page 2?</p>
|
[
{
"answer_id": 206091,
"author": "Khaled Sadek",
"author_id": 75122,
"author_profile": "https://wordpress.stackexchange.com/users/75122",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Update:</strong></p>\n\n<pre><code>add_action('pre_get_posts', 'category_query_offset', 1 );\nfunction category_query_offset($query) {\n // Before anything else, make sure this is the right query\n if (!$query->is_category('news')) {\n return;\n }\n\n // Next, determine paged\n $ppp = get_option('paged');\n}\n// Next, handle paged\nif($ppp > 1){\n $query->set('paged', $ppp-1);\n}\n</code></pre>\n\n<p>Try some thing like</p>\n\n<pre><code>$paged = ( get_query_var('paged') ) ? get_query_var('paged')-1 : 1;\n$args = array (\n 'paged' => $paged,\n);\n</code></pre>\n"
},
{
"answer_id": 206133,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>This is quite an interesting question (<em>which I have upvoted, specially for your approach and research</em>). The big curveball here is the first page of the query:</p>\n\n<ul>\n<li><p>You cannot set the query to return <code>0</code> posts on the first page</p></li>\n<li><p>By moving the page content of every page up by one page, you will loose the last page as the query will still only have the same amount of posts so the <code>$max_num_pages</code> property will still remain the same</p></li>\n</ul>\n\n<p>We will need to somehow \"trick\" the <code>WP_Query</code> class to return our posts corectly with the offset of one page, and also get the correct number of pages in order not to loose the last page in the query</p>\n\n<p>Lets look at the following idea and try to put everything in code. Before we do, I would however like to raise a few notes here</p>\n\n<h2>IMPORTANT NOTES:</h2>\n\n<ul>\n<li><p>Everything is untested, so it might be buggy. Make sure to test this locally with debug turned on</p></li>\n<li><p>The code requires at least PHP 5.3, any version below 5.3 will cause a fatal error. Note, if are still using any version below PHP 5.5, you should have upgraded long time ago already </p></li>\n<li><p>Modify and abuse the code as you see fit to suit your exact needs</p></li>\n</ul>\n\n<h2>THE LIGHTBULB IDEA:</h2>\n\n<p><strong>WHAT WE WILL NEED</strong></p>\n\n<p>In order to make everything work, we will need the following:</p>\n\n<ul>\n<li><p>The current page number being viewed</p></li>\n<li><p>The <code>posts_per_page</code> option set in reading settings</p></li>\n<li><p>Custom <code>offset</code></p></li>\n<li><p>Modify the <code>$found_posts</code> property of the query to correct the <code>$max_num_pages</code> property</p></li>\n</ul>\n\n<p>Pagination is <code>WP_Query</code> comes down a very simple few lines of code</p>\n\n<pre><code>if ( empty($q['nopaging']) && !$this->is_singular ) {\n $page = absint($q['paged']);\n if ( !$page )\n $page = 1;\n // If 'offset' is provided, it takes precedence over 'paged'.\n if ( isset( $q['offset'] ) && is_numeric( $q['offset'] ) ) {\n $q['offset'] = absint( $q['offset'] );\n $pgstrt = $q['offset'] . ', ';\n } else {\n $pgstrt = absint( ( $page - 1 ) * $q['posts_per_page'] ) . ', ';\n }\n $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];\n}\n</code></pre>\n\n<p>What basically happens, once an offset is explicitely set, the <code>paged</code> parameter is ignored. The first parameter of the SQL <code>LIMIT</code> clause is recalculated from the offset and will be the number of posts to be skipped in the generated SQL query. </p>\n\n<p>From your question, apparently when setting <code>offset</code> to <code>0</code>, the offset query fails, which is strange, as the following check should return true</p>\n\n<pre><code>if ( isset( $q['offset'] ) && is_numeric( $q['offset'] ) )\n</code></pre>\n\n<p><code>0</code>is a valid number and should return true. If this does not on your installation, you should debug the issue</p>\n\n<p>To come back to the issue at hand, we will use the same kind of logic to calculate and set our offset to get post 1 on page 2 and from there paginate the query. For the first page, we will not alter anything, so the posts that is suppose to be on page 1 will still be on page as normal, we would just need to \"hide\" them later on so that we do not display them on page 1</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $q )\n{\n if ( !is_admin() // Only target the front end, VERY VERY IMPORTANT\n && $q->is_main_query() // Only target the main query, VERY VERY IMPORTANT\n && $q->is_cateory( 'news' ) // Only target the news category\n ) {\n $current_page = $q->get( 'paged' ); // Get the current page number\n // We will only need to run this from page 2 onwards\n if ( $current_page != 0 ) { // You can also use if ( is_paged() ) {\n // Get the amount of posts per page\n $posts_per_page = get_option( 'posts_per_page' );\n // Recalculate our offset\n $offset = ( ( $current_page - 1) * $posts_per_page ) - $posts_per_page; // This should work on page 2 where it returns 0\n\n // Set our offset\n $q->set( 'offset', $offset );\n }\n }\n});\n</code></pre>\n\n<p>You should be seeing the same posts from page 1 on page 2. As I previously stated, if this does not happen, either <code>is_numeric( 0 )</code> is returning false (<em>which it should not</em>) or you have another <code>pre_get_posts</code> action that is also trying to set an offset or you are using making use of the <code>posts_*</code> clause filters (<em>more specifically, the <code>post_limits</code> filter</em>). This would be something you would need to debug by yourself.</p>\n\n<p>The next issue is to correct pagination, beacause as I previously stated, you will be a page short. For this, we will need to add the value of <code>get_option( 'posts_per_page' )</code> to the amount of posts found in the query as we are offsetting the query by that amount. by doing this, we are effectively adding <code>1</code> to the <code>$max_num_pages</code> property.</p>\n\n<pre><code>add_action( 'found_posts', function ( $found_posts, $q )\n{\n if ( !is_admin() // Only target the front end, VERY VERY IMPORTANT\n && $q->is_main_query() // Only target the main query, VERY VERY IMPORTANT\n && $q->is_cateory( 'news' ) // Only target the news category\n ) {\n $found_posts = $found_posts + get_option( 'posts_per_page');\n }\n}, 10, 2 );\n</code></pre>\n\n<p>This should sort everything, except the first page. </p>\n\n<h2>ALL TOGETHER NOW (<em>and specially for @ialocin - <a href=\"http://www.youtube.com/watch?v=OkQA9OsJhPQ\">Yellow Submarine</a></em>)</h2>\n\n<p>This should all go into <code>functions.php</code></p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $q )\n{\n if ( !is_admin() // Only target the front end, VERY VERY IMPORTANT\n && $q->is_main_query() // Only target the main query, VERY VERY IMPORTANT\n && $q->is_cateory( 'news' ) // Only target the news category\n ) {\n $current_page = $q->get( 'paged' ); // Get the current page number\n // We will only need to run this from page 2 onwards\n if ( $current_page != 0 ) { // You can also use if ( is_paged() ) {\n // Get the amount of posts per page\n $posts_per_page = get_option( 'posts_per_page' );\n // Recalculate our offset\n $offset = ( ( $current_page - 1) * $posts_per_page ) - $posts_per_page; // This should work on page 2 where it returns 0\n\n // Set our offset\n $q->set( 'offset', $offset );\n }\n }\n});\n\nadd_filter( 'found_posts', function ( $found_posts, $q )\n{\n if ( !is_admin() // Only target the front end, VERY VERY IMPORTANT\n && $q->is_main_query() // Only target the main query, VERY VERY IMPORTANT\n && $q->is_cateory( 'news' ) // Only target the news category\n ) {\n $found_posts = $found_posts + get_option( 'posts_per_page');\n }\n return $found_posts;\n}, 10, 2 );\n</code></pre>\n\n<h2>FIRST PAGE OPTIONS</h2>\n\n<p>There are a few options here:</p>\n\n<p><strong>OPTION 1</strong></p>\n\n<p>I would most probably go for this option. What you would want to do here is to create a <code>category-news.php</code> (<em>if you haven't yet done this</em>). This will be the template that will be used whenever the <code>news</code> category is viewed. This template will be very simply</p>\n\n<p>Example</p>\n\n<pre><code><?php\nget_header()\n\nif ( !is_paged() ) { // This is the first page\n get_template_part( 'news', 'special' );\n} else { // This is not the first page\n get_template_part( 'news', 'loop' );\n}\n\nget_sidebar();\nget_footer();\n</code></pre>\n\n<p>As you can see, I have included two template parts, <code>news-special.php</code> and <code>news-loop.php</code>. Now, the basics of the two custom templates are:</p>\n\n<ul>\n<li><p><code>news-special.php</code> -> This template part will be whatever you would want to display on the first page. Add all your custom static info here. Be very careful not to call the loop in this template as this would display the posts of the first page. </p></li>\n<li><p><code>news-loop.php</code> -> This is the template where we will invoke the loop. This section will look something like this:</p>\n\n<pre><code>global $wp_query;\nwhile ( have_posts() ) {\nthe_post();\n\n // Your template tags and markup\n\n}\n</code></pre></li>\n</ul>\n\n<h2>OPTION 2</h2>\n\n<p>Create a separate template with your static content and simply use the <code>category_template</code> filter to use this template when we view the first page of the <code>news</code> category. Also, be sure not to invoke the default loop in this template. Also, make sure that your naming convention here does not collide with template names within the template hierarchy</p>\n\n<p>I hope this is useful. Feel free toleave comments with concerns</p>\n\n<h2>EDIT</h2>\n\n<p>Thanks to the OP, there is a definite bug in the <code>WP_Query</code> class, check the <a href=\"https://core.trac.wordpress.org/ticket/34060\">trac ticket #34060</a>. The code I have posted is from Wordpress v4.4, and the bug is fixed in this version.</p>\n\n<p>I went back to the source code of v4.3, where the bug is, and I can confirm that <code>0</code> is ignored when set as value to <code>offset</code> as the code simply checks whether the <code>offset</code> parameter is <code>empty</code>. <code>0</code> is taken as empty in PHP. I am not sure if this behavior (bug) is only found in v4.3 only or in all previous versions (according to the ticket, this bug is in v4.3), but there is a patch for this bug which you can check out in the trac ticket. Like I said, this bug has definitely being fixed in v4.4</p>\n"
}
] |
2015/10/20
|
[
"https://wordpress.stackexchange.com/questions/206083",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82243/"
] |
I'm trying to create a category template in my theme that will display static content if the user is on the first page of the archive, and then display the posts in the category on the following pages. I'm basically trying to replicate the category behavior on Wired.com where <http://www.wired.com/category/design> is a landing page while /category/design/page/1 shows a reverse chronological listing of posts like you would expect on a category archive.
The key here is that I'm not showing any posts from the category archive on the first page, so I need the next page to start with the first post. I first tried doing this using [offset and manual pagination](https://codex.wordpress.org/Making_Custom_Queries_using_Offset_and_Pagination) by setting the offset of the query to 0 if the 'paged' query var was 2. But offset is ignored when it's set to zero, so the best I can do is set the offset to 1 and start with the second post in the category.
This is what I added to functions.php:
```
add_action('pre_get_posts', 'category_query_offset', 1 );
function category_query_offset(&$query) {
// Before anything else, make sure this is the right query
if (!$query->is_category('news')) {
return;
}
// Next, determine how many posts per page
$ppp = get_option('posts_per_page');
//Next, detect and handle pagination
if ($query->is_paged) {
// Manually determine page query offset
$page_offset = (($query->query_vars['paged']-1) * $ppp) - $ppp;
// Apply adjust page offset
$query->set('offset', $page_offset );
}
}
```
What would be better, and what it appears *Wired* does, is to use the default pagination so the posts start on page 1, but insert a page 0 for the static content. Hypothetically, this seems like it would be possible by displaying the static content if 'paged' is 0, and displaying the first page of posts if 'paged' is 1. The problem is that 'paged' is never 1 because Wordpress sets 'paged' to zero when the user requests the first page. That means 'paged' is 0 for both /category/news/page/1 and /category/news.
Is there a way to check if the user requested /category/news/page/1 as opposed to /category/news? Failing that, is there a way to display all the posts in the category starting on page 2?
|
This is quite an interesting question (*which I have upvoted, specially for your approach and research*). The big curveball here is the first page of the query:
* You cannot set the query to return `0` posts on the first page
* By moving the page content of every page up by one page, you will loose the last page as the query will still only have the same amount of posts so the `$max_num_pages` property will still remain the same
We will need to somehow "trick" the `WP_Query` class to return our posts corectly with the offset of one page, and also get the correct number of pages in order not to loose the last page in the query
Lets look at the following idea and try to put everything in code. Before we do, I would however like to raise a few notes here
IMPORTANT NOTES:
----------------
* Everything is untested, so it might be buggy. Make sure to test this locally with debug turned on
* The code requires at least PHP 5.3, any version below 5.3 will cause a fatal error. Note, if are still using any version below PHP 5.5, you should have upgraded long time ago already
* Modify and abuse the code as you see fit to suit your exact needs
THE LIGHTBULB IDEA:
-------------------
**WHAT WE WILL NEED**
In order to make everything work, we will need the following:
* The current page number being viewed
* The `posts_per_page` option set in reading settings
* Custom `offset`
* Modify the `$found_posts` property of the query to correct the `$max_num_pages` property
Pagination is `WP_Query` comes down a very simple few lines of code
```
if ( empty($q['nopaging']) && !$this->is_singular ) {
$page = absint($q['paged']);
if ( !$page )
$page = 1;
// If 'offset' is provided, it takes precedence over 'paged'.
if ( isset( $q['offset'] ) && is_numeric( $q['offset'] ) ) {
$q['offset'] = absint( $q['offset'] );
$pgstrt = $q['offset'] . ', ';
} else {
$pgstrt = absint( ( $page - 1 ) * $q['posts_per_page'] ) . ', ';
}
$limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
}
```
What basically happens, once an offset is explicitely set, the `paged` parameter is ignored. The first parameter of the SQL `LIMIT` clause is recalculated from the offset and will be the number of posts to be skipped in the generated SQL query.
From your question, apparently when setting `offset` to `0`, the offset query fails, which is strange, as the following check should return true
```
if ( isset( $q['offset'] ) && is_numeric( $q['offset'] ) )
```
`0`is a valid number and should return true. If this does not on your installation, you should debug the issue
To come back to the issue at hand, we will use the same kind of logic to calculate and set our offset to get post 1 on page 2 and from there paginate the query. For the first page, we will not alter anything, so the posts that is suppose to be on page 1 will still be on page as normal, we would just need to "hide" them later on so that we do not display them on page 1
```
add_action( 'pre_get_posts', function ( $q )
{
if ( !is_admin() // Only target the front end, VERY VERY IMPORTANT
&& $q->is_main_query() // Only target the main query, VERY VERY IMPORTANT
&& $q->is_cateory( 'news' ) // Only target the news category
) {
$current_page = $q->get( 'paged' ); // Get the current page number
// We will only need to run this from page 2 onwards
if ( $current_page != 0 ) { // You can also use if ( is_paged() ) {
// Get the amount of posts per page
$posts_per_page = get_option( 'posts_per_page' );
// Recalculate our offset
$offset = ( ( $current_page - 1) * $posts_per_page ) - $posts_per_page; // This should work on page 2 where it returns 0
// Set our offset
$q->set( 'offset', $offset );
}
}
});
```
You should be seeing the same posts from page 1 on page 2. As I previously stated, if this does not happen, either `is_numeric( 0 )` is returning false (*which it should not*) or you have another `pre_get_posts` action that is also trying to set an offset or you are using making use of the `posts_*` clause filters (*more specifically, the `post_limits` filter*). This would be something you would need to debug by yourself.
The next issue is to correct pagination, beacause as I previously stated, you will be a page short. For this, we will need to add the value of `get_option( 'posts_per_page' )` to the amount of posts found in the query as we are offsetting the query by that amount. by doing this, we are effectively adding `1` to the `$max_num_pages` property.
```
add_action( 'found_posts', function ( $found_posts, $q )
{
if ( !is_admin() // Only target the front end, VERY VERY IMPORTANT
&& $q->is_main_query() // Only target the main query, VERY VERY IMPORTANT
&& $q->is_cateory( 'news' ) // Only target the news category
) {
$found_posts = $found_posts + get_option( 'posts_per_page');
}
}, 10, 2 );
```
This should sort everything, except the first page.
ALL TOGETHER NOW (*and specially for @ialocin - [Yellow Submarine](http://www.youtube.com/watch?v=OkQA9OsJhPQ)*)
----------------------------------------------------------------------------------------------------------------
This should all go into `functions.php`
```
add_action( 'pre_get_posts', function ( $q )
{
if ( !is_admin() // Only target the front end, VERY VERY IMPORTANT
&& $q->is_main_query() // Only target the main query, VERY VERY IMPORTANT
&& $q->is_cateory( 'news' ) // Only target the news category
) {
$current_page = $q->get( 'paged' ); // Get the current page number
// We will only need to run this from page 2 onwards
if ( $current_page != 0 ) { // You can also use if ( is_paged() ) {
// Get the amount of posts per page
$posts_per_page = get_option( 'posts_per_page' );
// Recalculate our offset
$offset = ( ( $current_page - 1) * $posts_per_page ) - $posts_per_page; // This should work on page 2 where it returns 0
// Set our offset
$q->set( 'offset', $offset );
}
}
});
add_filter( 'found_posts', function ( $found_posts, $q )
{
if ( !is_admin() // Only target the front end, VERY VERY IMPORTANT
&& $q->is_main_query() // Only target the main query, VERY VERY IMPORTANT
&& $q->is_cateory( 'news' ) // Only target the news category
) {
$found_posts = $found_posts + get_option( 'posts_per_page');
}
return $found_posts;
}, 10, 2 );
```
FIRST PAGE OPTIONS
------------------
There are a few options here:
**OPTION 1**
I would most probably go for this option. What you would want to do here is to create a `category-news.php` (*if you haven't yet done this*). This will be the template that will be used whenever the `news` category is viewed. This template will be very simply
Example
```
<?php
get_header()
if ( !is_paged() ) { // This is the first page
get_template_part( 'news', 'special' );
} else { // This is not the first page
get_template_part( 'news', 'loop' );
}
get_sidebar();
get_footer();
```
As you can see, I have included two template parts, `news-special.php` and `news-loop.php`. Now, the basics of the two custom templates are:
* `news-special.php` -> This template part will be whatever you would want to display on the first page. Add all your custom static info here. Be very careful not to call the loop in this template as this would display the posts of the first page.
* `news-loop.php` -> This is the template where we will invoke the loop. This section will look something like this:
```
global $wp_query;
while ( have_posts() ) {
the_post();
// Your template tags and markup
}
```
OPTION 2
--------
Create a separate template with your static content and simply use the `category_template` filter to use this template when we view the first page of the `news` category. Also, be sure not to invoke the default loop in this template. Also, make sure that your naming convention here does not collide with template names within the template hierarchy
I hope this is useful. Feel free toleave comments with concerns
EDIT
----
Thanks to the OP, there is a definite bug in the `WP_Query` class, check the [trac ticket #34060](https://core.trac.wordpress.org/ticket/34060). The code I have posted is from Wordpress v4.4, and the bug is fixed in this version.
I went back to the source code of v4.3, where the bug is, and I can confirm that `0` is ignored when set as value to `offset` as the code simply checks whether the `offset` parameter is `empty`. `0` is taken as empty in PHP. I am not sure if this behavior (bug) is only found in v4.3 only or in all previous versions (according to the ticket, this bug is in v4.3), but there is a patch for this bug which you can check out in the trac ticket. Like I said, this bug has definitely being fixed in v4.4
|
206,121 |
<p>I've created a custom taxonomy register as the code below, but it does not find the taxonomy-specialty.php nor archive.php templates (page not found error).</p>
<p>I did following (as recommended by other threads found on SE and the web):
- re-save the permalinks
- find the taxonomy settings page in wp-admin and when I hover over 'View' it points me to 'mysite.com/events/specialties/footology' for a 'Footology' taxonomy entry I created for a post of type 'event' - so the URL is as expected. However when visiting the link still get page not found error.</p>
<pre><code>$specialty_args = array(
'hierarchical' => false,
// This array of options controls the labels displayed in the WordPress Admin UI
'labels' => array(
'name' => 'Specialty',
'singular_name' => 'Specialty',
'search_items' => 'Search specialties',
'all_items' => 'All specialties',
'edit_item' => 'Edit specialty',
'update_item' => 'Update specialty',
'add_new_item' => 'Add new specialty',
'new_item_name' => 'New specialty name',
'menu_name' => 'Specialties',
),
'show_ui' => true,
'show_admin_column' => true,
'query_var' => 'specialty',
// Control the slugs used for this taxonomy
'rewrite' => array(
'slug' => 'events/specialties', // This controls the base slug that will display before each term
'with_front' => false, // Don't display the category base before "/specialties/"
'hierarchical' => false
),
);
register_taxonomy('specialty', 'event', $specialty_args);
register_taxonomy_for_object_type('specialty', 'event'); //says in https://codex.wordpress.org/Function_Reference/register_taxonomy under 'Usage' to do this
</code></pre>
<p>I don't know what is wrong. Help appreciated, thank you!</p>
|
[
{
"answer_id": 206122,
"author": "Por",
"author_id": 31832,
"author_profile": "https://wordpress.stackexchange.com/users/31832",
"pm_score": -1,
"selected": false,
"text": "<pre><code>'show_ui' => true,\n'show_admin_column' => true,\n'query_var' => 'specialty',\n'has_archive' => true, //make sure you have added this one\n</code></pre>\n\n<p>What is your archive name? What is your archive url? Actually, your archive file name should be like that archive-specialty.php, your post type archive url will be like this yourdomain.com/events/specialties. I have tested, it should work on yours.</p>\n\n<p>If you are not sure about custom post type, use <a href=\"http://wordpress.org/plugins/types/\" rel=\"nofollow\">wordpress type plugin</a> or use <a href=\"https://generatewp.com/post-type/\" rel=\"nofollow\">wordpress generator</a></p>\n"
},
{
"answer_id": 206129,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 1,
"selected": false,
"text": "<p>The page not found error doesn't mean that the template file is not found/used. Note that a URL returns a 404 status header (not found), then 404.php is used (or index.php if 404.php doesn't exist).</p>\n\n<p>I think your real problem is that you have not flushed the rewrite rules after the taxonomy has been registered. To do it, follow these steps:</p>\n\n<p><strong>Manually</strong>: go to settings->permalinks and click the save button (you don't need to change anything, just click the save button).</p>\n\n<p><strong>Auto</strong>: in your plugin, use <code>flush_rewrite_rules()</code> during plugin activation hook (never use <code>flush_rewrite_rules()</code> on every page load). For example:</p>\n\n<pre><code>register_activation_hook( __FILE__, 'cyb_plugin_activation' );\nfunction cyb_plugin_activation() {\n\n cyb_register_taxonomy();\n flush_rewrite_rules();\n\n}\n\nadd_action( 'init', 'cyb_register_taxonomy' );\nfunction cyb_register_taxonomy() {\n\n $specialty_args = array(\n 'hierarchical' => false,\n // This array of options controls the labels displayed in the WordPress Admin UI\n 'labels' => array(\n 'name' => 'Specialty',\n 'singular_name' => 'Specialty',\n 'search_items' => 'Search specialties',\n 'all_items' => 'All specialties',\n 'edit_item' => 'Edit specialty',\n 'update_item' => 'Update specialty',\n 'add_new_item' => 'Add new specialty',\n 'new_item_name' => 'New specialty name',\n 'menu_name' => 'Specialties',\n ),\n\n 'show_ui' => true,\n 'show_admin_column' => true,\n 'query_var' => 'specialty',\n\n // Control the slugs used for this taxonomy\n 'rewrite' => array(\n 'slug' => 'events/specialty', // This controls the base slug that will display before each term (renamed to specialty from specialties)\n 'with_front' => false, // Don't display the category base before \"/specialties/\"\n 'hierarchical' => false\n ),\n );\n\n register_taxonomy('specialty', 'event', $specialty_args);\n register_taxonomy_for_object_type('specialty', 'event');\n\n}\n\nregister_deactivation_hook( __FILE__, 'cyb_plugin_deactivation' );\nfunction cyb_plugin_deactivation() {\n\n // Flush the rewrite rules also on deactivation\n flush_rewrite_rules();\n\n}\n</code></pre>\n"
}
] |
2015/10/21
|
[
"https://wordpress.stackexchange.com/questions/206121",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51271/"
] |
I've created a custom taxonomy register as the code below, but it does not find the taxonomy-specialty.php nor archive.php templates (page not found error).
I did following (as recommended by other threads found on SE and the web):
- re-save the permalinks
- find the taxonomy settings page in wp-admin and when I hover over 'View' it points me to 'mysite.com/events/specialties/footology' for a 'Footology' taxonomy entry I created for a post of type 'event' - so the URL is as expected. However when visiting the link still get page not found error.
```
$specialty_args = array(
'hierarchical' => false,
// This array of options controls the labels displayed in the WordPress Admin UI
'labels' => array(
'name' => 'Specialty',
'singular_name' => 'Specialty',
'search_items' => 'Search specialties',
'all_items' => 'All specialties',
'edit_item' => 'Edit specialty',
'update_item' => 'Update specialty',
'add_new_item' => 'Add new specialty',
'new_item_name' => 'New specialty name',
'menu_name' => 'Specialties',
),
'show_ui' => true,
'show_admin_column' => true,
'query_var' => 'specialty',
// Control the slugs used for this taxonomy
'rewrite' => array(
'slug' => 'events/specialties', // This controls the base slug that will display before each term
'with_front' => false, // Don't display the category base before "/specialties/"
'hierarchical' => false
),
);
register_taxonomy('specialty', 'event', $specialty_args);
register_taxonomy_for_object_type('specialty', 'event'); //says in https://codex.wordpress.org/Function_Reference/register_taxonomy under 'Usage' to do this
```
I don't know what is wrong. Help appreciated, thank you!
|
The page not found error doesn't mean that the template file is not found/used. Note that a URL returns a 404 status header (not found), then 404.php is used (or index.php if 404.php doesn't exist).
I think your real problem is that you have not flushed the rewrite rules after the taxonomy has been registered. To do it, follow these steps:
**Manually**: go to settings->permalinks and click the save button (you don't need to change anything, just click the save button).
**Auto**: in your plugin, use `flush_rewrite_rules()` during plugin activation hook (never use `flush_rewrite_rules()` on every page load). For example:
```
register_activation_hook( __FILE__, 'cyb_plugin_activation' );
function cyb_plugin_activation() {
cyb_register_taxonomy();
flush_rewrite_rules();
}
add_action( 'init', 'cyb_register_taxonomy' );
function cyb_register_taxonomy() {
$specialty_args = array(
'hierarchical' => false,
// This array of options controls the labels displayed in the WordPress Admin UI
'labels' => array(
'name' => 'Specialty',
'singular_name' => 'Specialty',
'search_items' => 'Search specialties',
'all_items' => 'All specialties',
'edit_item' => 'Edit specialty',
'update_item' => 'Update specialty',
'add_new_item' => 'Add new specialty',
'new_item_name' => 'New specialty name',
'menu_name' => 'Specialties',
),
'show_ui' => true,
'show_admin_column' => true,
'query_var' => 'specialty',
// Control the slugs used for this taxonomy
'rewrite' => array(
'slug' => 'events/specialty', // This controls the base slug that will display before each term (renamed to specialty from specialties)
'with_front' => false, // Don't display the category base before "/specialties/"
'hierarchical' => false
),
);
register_taxonomy('specialty', 'event', $specialty_args);
register_taxonomy_for_object_type('specialty', 'event');
}
register_deactivation_hook( __FILE__, 'cyb_plugin_deactivation' );
function cyb_plugin_deactivation() {
// Flush the rewrite rules also on deactivation
flush_rewrite_rules();
}
```
|
206,140 |
<p>I have a form where i would like to add a <code>datetimepicker()</code>.
I must be doing something wrong.</p>
<p>I have done the following:
In my <code>header.php</code></p>
<pre><code><?php wp_enqueue_script("jquery"); ?>
</code></pre>
<p>In my <code>functions.php</code></p>
<pre><code>wp_enqueue_script('jquery-ui-datepicker');
wp_enqueue_style('jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');
</code></pre>
<p>In my <code>template.php</code></p>
<pre><code><form id="" name="" action="<?php echo get_permalink(); ?>" method="post">
<input type="text" id="MyDate" name="MyDate" value=""/>
<input type="submit" value="Submit" name="submit">
</form>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#MyDate').datepicker({
dateFormat : 'dd-mm-yy'
});
});
</script>
</code></pre>
<p>Here is the error:</p>
<pre><code>Uncaught TypeError: jQuery(...).datepicker is not a function
</code></pre>
<p>I see the <code><input></code> element but if I click in it nothing happens.<br>
This all comes from the following <a href="https://wordpress.org/support/topic/how-to-add-jquery-datepicker" rel="nofollow">link</a></p>
<p>Hope anyone sees my mistake(s)!<br>
M.</p>
|
[
{
"answer_id": 206142,
"author": "websupporter",
"author_id": 48693,
"author_profile": "https://wordpress.stackexchange.com/users/48693",
"pm_score": 0,
"selected": false,
"text": "<p>I guess, the scripts are loaded in the footer action while your script is loaded before.</p>\n\n<p>So, what I would try:\nAdd your scripts via th proper action: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"nofollow\"><code>wp_enqueue_scripts</code></a> </p>\n\n<pre><code>function wpse_206140_enqueue_script() {\n wp_enqueue_script( 'jquery-ui-datepicker' );\n wp_enqueue_style( 'jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css' );\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_206140_enqueue_script' );\n</code></pre>\n\n<p>If you still run into the problem: Consider to external your script into a file and enqueue this file in dependency of <code>jquery-ui-datepicker</code>, see <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">here</a>.</p>\n\n<p><strong>Also: Check wp_head() and wp_footer()</strong>\nAnother possible reason could be, your theme does not execute the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head\" rel=\"nofollow\"><code>wp_head</code></a> and <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_footer\" rel=\"nofollow\"><code>wp_footer</code></a> actions. Check your header.php and footer.php for <code>wp_header()</code> and <code>wp_footer()</code>. These functions need to be placed there.</p>\n\n<p>Hope, this helps.</p>\n"
},
{
"answer_id": 206183,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 0,
"selected": false,
"text": "<p>Try using the <code>wp_print_footer_scripts</code> action (front-end) or <code>admin_print_footer_scripts</code> action (back-end) with a large priority to ensure your javascript gets executed as late as possible, eg</p>\n\n<pre><code>add_action( 'wp_print_footer_scripts', function () {\n ?>\n <script type=\"text/javascript\">\n jQuery(document).ready(function() {\n jQuery('#MyDate').datepicker({\n dateFormat : 'dd-mm-yy'\n });\n });\n </script>\n <?php\n}, 50 );\n</code></pre>\n\n<p>(cf <a href=\"https://wordpress.stackexchange.com/a/175855/57034\">https://wordpress.stackexchange.com/a/175855/57034</a>)</p>\n"
},
{
"answer_id": 309887,
"author": "Quang Hoang",
"author_id": 134874,
"author_profile": "https://wordpress.stackexchange.com/users/134874",
"pm_score": 1,
"selected": false,
"text": "<p>You can try this.</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpcustom_enqueue_script' );\nfunction wpcustom_enqueue_script() {\n wp_enqueue_style( 'datepicker-style', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css' );\n wp_enqueue_script( 'js-datepicker', 'https://code.jquery.com/ui/1.12.1/jquery-ui.js', array('jquery'), null, true); \n}\n</code></pre>\n\n<p>Readmore: <a href=\"http://jqueryui.com/datepicker/\" rel=\"nofollow noreferrer\">http://jqueryui.com/datepicker/</a></p>\n"
}
] |
2015/10/21
|
[
"https://wordpress.stackexchange.com/questions/206140",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52240/"
] |
I have a form where i would like to add a `datetimepicker()`.
I must be doing something wrong.
I have done the following:
In my `header.php`
```
<?php wp_enqueue_script("jquery"); ?>
```
In my `functions.php`
```
wp_enqueue_script('jquery-ui-datepicker');
wp_enqueue_style('jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');
```
In my `template.php`
```
<form id="" name="" action="<?php echo get_permalink(); ?>" method="post">
<input type="text" id="MyDate" name="MyDate" value=""/>
<input type="submit" value="Submit" name="submit">
</form>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#MyDate').datepicker({
dateFormat : 'dd-mm-yy'
});
});
</script>
```
Here is the error:
```
Uncaught TypeError: jQuery(...).datepicker is not a function
```
I see the `<input>` element but if I click in it nothing happens.
This all comes from the following [link](https://wordpress.org/support/topic/how-to-add-jquery-datepicker)
Hope anyone sees my mistake(s)!
M.
|
You can try this.
```
add_action( 'wp_enqueue_scripts', 'wpcustom_enqueue_script' );
function wpcustom_enqueue_script() {
wp_enqueue_style( 'datepicker-style', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css' );
wp_enqueue_script( 'js-datepicker', 'https://code.jquery.com/ui/1.12.1/jquery-ui.js', array('jquery'), null, true);
}
```
Readmore: <http://jqueryui.com/datepicker/>
|
206,147 |
<p>I have to create Web services for android app using WordPress Database. where user can login and register using android app. that record will be saved in WordPress database. display All the posts of wordpress site in android app using wordpress database table. user can Create and Update User Profile ,Login , Register ,Posts etc. </p>
<p>I want to Know any WordPress API or web services Plugin is there which can interact with WordPress Tables. Any help would be appreciated.</p>
|
[
{
"answer_id": 206142,
"author": "websupporter",
"author_id": 48693,
"author_profile": "https://wordpress.stackexchange.com/users/48693",
"pm_score": 0,
"selected": false,
"text": "<p>I guess, the scripts are loaded in the footer action while your script is loaded before.</p>\n\n<p>So, what I would try:\nAdd your scripts via th proper action: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"nofollow\"><code>wp_enqueue_scripts</code></a> </p>\n\n<pre><code>function wpse_206140_enqueue_script() {\n wp_enqueue_script( 'jquery-ui-datepicker' );\n wp_enqueue_style( 'jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css' );\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_206140_enqueue_script' );\n</code></pre>\n\n<p>If you still run into the problem: Consider to external your script into a file and enqueue this file in dependency of <code>jquery-ui-datepicker</code>, see <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">here</a>.</p>\n\n<p><strong>Also: Check wp_head() and wp_footer()</strong>\nAnother possible reason could be, your theme does not execute the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head\" rel=\"nofollow\"><code>wp_head</code></a> and <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_footer\" rel=\"nofollow\"><code>wp_footer</code></a> actions. Check your header.php and footer.php for <code>wp_header()</code> and <code>wp_footer()</code>. These functions need to be placed there.</p>\n\n<p>Hope, this helps.</p>\n"
},
{
"answer_id": 206183,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 0,
"selected": false,
"text": "<p>Try using the <code>wp_print_footer_scripts</code> action (front-end) or <code>admin_print_footer_scripts</code> action (back-end) with a large priority to ensure your javascript gets executed as late as possible, eg</p>\n\n<pre><code>add_action( 'wp_print_footer_scripts', function () {\n ?>\n <script type=\"text/javascript\">\n jQuery(document).ready(function() {\n jQuery('#MyDate').datepicker({\n dateFormat : 'dd-mm-yy'\n });\n });\n </script>\n <?php\n}, 50 );\n</code></pre>\n\n<p>(cf <a href=\"https://wordpress.stackexchange.com/a/175855/57034\">https://wordpress.stackexchange.com/a/175855/57034</a>)</p>\n"
},
{
"answer_id": 309887,
"author": "Quang Hoang",
"author_id": 134874,
"author_profile": "https://wordpress.stackexchange.com/users/134874",
"pm_score": 1,
"selected": false,
"text": "<p>You can try this.</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpcustom_enqueue_script' );\nfunction wpcustom_enqueue_script() {\n wp_enqueue_style( 'datepicker-style', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css' );\n wp_enqueue_script( 'js-datepicker', 'https://code.jquery.com/ui/1.12.1/jquery-ui.js', array('jquery'), null, true); \n}\n</code></pre>\n\n<p>Readmore: <a href=\"http://jqueryui.com/datepicker/\" rel=\"nofollow noreferrer\">http://jqueryui.com/datepicker/</a></p>\n"
}
] |
2015/10/21
|
[
"https://wordpress.stackexchange.com/questions/206147",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82282/"
] |
I have to create Web services for android app using WordPress Database. where user can login and register using android app. that record will be saved in WordPress database. display All the posts of wordpress site in android app using wordpress database table. user can Create and Update User Profile ,Login , Register ,Posts etc.
I want to Know any WordPress API or web services Plugin is there which can interact with WordPress Tables. Any help would be appreciated.
|
You can try this.
```
add_action( 'wp_enqueue_scripts', 'wpcustom_enqueue_script' );
function wpcustom_enqueue_script() {
wp_enqueue_style( 'datepicker-style', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css' );
wp_enqueue_script( 'js-datepicker', 'https://code.jquery.com/ui/1.12.1/jquery-ui.js', array('jquery'), null, true);
}
```
Readmore: <http://jqueryui.com/datepicker/>
|
206,155 |
<p>If I do a query of the post table for post type 'attachment' sometimes the guid field will contain an attachment id, "<a href="http://sitename.com/?attachment_id=1201" rel="nofollow">http://sitename.com/?attachment_id=1201</a>", instead of a URL. How can I convert a string like this into the attachment url?</p>
|
[
{
"answer_id": 206142,
"author": "websupporter",
"author_id": 48693,
"author_profile": "https://wordpress.stackexchange.com/users/48693",
"pm_score": 0,
"selected": false,
"text": "<p>I guess, the scripts are loaded in the footer action while your script is loaded before.</p>\n\n<p>So, what I would try:\nAdd your scripts via th proper action: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"nofollow\"><code>wp_enqueue_scripts</code></a> </p>\n\n<pre><code>function wpse_206140_enqueue_script() {\n wp_enqueue_script( 'jquery-ui-datepicker' );\n wp_enqueue_style( 'jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css' );\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_206140_enqueue_script' );\n</code></pre>\n\n<p>If you still run into the problem: Consider to external your script into a file and enqueue this file in dependency of <code>jquery-ui-datepicker</code>, see <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">here</a>.</p>\n\n<p><strong>Also: Check wp_head() and wp_footer()</strong>\nAnother possible reason could be, your theme does not execute the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head\" rel=\"nofollow\"><code>wp_head</code></a> and <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_footer\" rel=\"nofollow\"><code>wp_footer</code></a> actions. Check your header.php and footer.php for <code>wp_header()</code> and <code>wp_footer()</code>. These functions need to be placed there.</p>\n\n<p>Hope, this helps.</p>\n"
},
{
"answer_id": 206183,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 0,
"selected": false,
"text": "<p>Try using the <code>wp_print_footer_scripts</code> action (front-end) or <code>admin_print_footer_scripts</code> action (back-end) with a large priority to ensure your javascript gets executed as late as possible, eg</p>\n\n<pre><code>add_action( 'wp_print_footer_scripts', function () {\n ?>\n <script type=\"text/javascript\">\n jQuery(document).ready(function() {\n jQuery('#MyDate').datepicker({\n dateFormat : 'dd-mm-yy'\n });\n });\n </script>\n <?php\n}, 50 );\n</code></pre>\n\n<p>(cf <a href=\"https://wordpress.stackexchange.com/a/175855/57034\">https://wordpress.stackexchange.com/a/175855/57034</a>)</p>\n"
},
{
"answer_id": 309887,
"author": "Quang Hoang",
"author_id": 134874,
"author_profile": "https://wordpress.stackexchange.com/users/134874",
"pm_score": 1,
"selected": false,
"text": "<p>You can try this.</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpcustom_enqueue_script' );\nfunction wpcustom_enqueue_script() {\n wp_enqueue_style( 'datepicker-style', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css' );\n wp_enqueue_script( 'js-datepicker', 'https://code.jquery.com/ui/1.12.1/jquery-ui.js', array('jquery'), null, true); \n}\n</code></pre>\n\n<p>Readmore: <a href=\"http://jqueryui.com/datepicker/\" rel=\"nofollow noreferrer\">http://jqueryui.com/datepicker/</a></p>\n"
}
] |
2015/10/21
|
[
"https://wordpress.stackexchange.com/questions/206155",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17097/"
] |
If I do a query of the post table for post type 'attachment' sometimes the guid field will contain an attachment id, "<http://sitename.com/?attachment_id=1201>", instead of a URL. How can I convert a string like this into the attachment url?
|
You can try this.
```
add_action( 'wp_enqueue_scripts', 'wpcustom_enqueue_script' );
function wpcustom_enqueue_script() {
wp_enqueue_style( 'datepicker-style', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css' );
wp_enqueue_script( 'js-datepicker', 'https://code.jquery.com/ui/1.12.1/jquery-ui.js', array('jquery'), null, true);
}
```
Readmore: <http://jqueryui.com/datepicker/>
|
206,158 |
<p>Having formulated my $query for a custom taxonomy on a page template, how would I ask if a specific term has posts?</p>
<pre><code>$args = array(
'post_type' => 'exhibitions',
'tax_query' => array(
array(
'taxonomy' => 'exhibition',
'field' => 'slug'
),
)
);
$query = new WP_Query($args);
</code></pre>
<p>Assuming I'm on the right track, a verbal description of the sort of conditional statements I'm looking for would be:</p>
<p>if the $query taxonomy term 'current' have posts, do something;</p>
<p>elseif the $query taxonomy term 'upcoming' have posts, do something else;</p>
|
[
{
"answer_id": 206166,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like you want <a href=\"https://codex.wordpress.org/Function_Reference/has_term\" rel=\"nofollow\"><code>has_term()</code></a>. Something like:\nFeed your query an array of terms:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'exhibitions',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'exhibition',\n 'field' => 'slug',\n 'terms' => array(\n 'current',\n 'upcoming',\n ),\n ),\n )\n);\n$query = new WP_Query($args);\n</code></pre>\n\n<p>Then loop over it multiple times:</p>\n\n<pre><code>if ($query->have_posts()) {\n while ($query->have_posts()) {\n $query->the_post();\n if (has_term('current','exhibition')) {\n // stuff\n }\n }\n}\n$query->rewind_posts();\nif ($query->have_posts()) {\n while ($query->have_posts()) {\n $query->the_post();\n if (has_term('upcoming','exhibition')) {\n // stuff\n }\n }\n}\n$query->rewind_posts();\n</code></pre>\n"
},
{
"answer_id": 206171,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 1,
"selected": true,
"text": "<p>I'm not sure what you exactly need, but normally, by default, <code>get_terms</code> returns only terms that actually have posts assigned to them</p>\n\n<pre><code>$terms = get_terms( 'exhibition' );\nvar_dump( $terms );\n</code></pre>\n\n<p>Apart from this, I really do not know what you exactly need</p>\n"
}
] |
2015/10/21
|
[
"https://wordpress.stackexchange.com/questions/206158",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51609/"
] |
Having formulated my $query for a custom taxonomy on a page template, how would I ask if a specific term has posts?
```
$args = array(
'post_type' => 'exhibitions',
'tax_query' => array(
array(
'taxonomy' => 'exhibition',
'field' => 'slug'
),
)
);
$query = new WP_Query($args);
```
Assuming I'm on the right track, a verbal description of the sort of conditional statements I'm looking for would be:
if the $query taxonomy term 'current' have posts, do something;
elseif the $query taxonomy term 'upcoming' have posts, do something else;
|
I'm not sure what you exactly need, but normally, by default, `get_terms` returns only terms that actually have posts assigned to them
```
$terms = get_terms( 'exhibition' );
var_dump( $terms );
```
Apart from this, I really do not know what you exactly need
|
206,167 |
<p>Ok, I've literally copy-pasted different enqueueing code from about 5 different sources (Including wordpress), and not a single one works.</p>
<p>Here's the code I'm using in functions.php:</p>
<pre><code><?php
function my_theme_scripts() {
wp_register_script(
'main',
get_stylesheet_directory_uri() . '/js/main.js',
array( 'jquery' ), '1.0.0', true
);
wp_enqueue_script('main');
}
add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );
?>
</code></pre>
<p>and it literally does nothing. No scripts added into my HTML. nothing.</p>
<p>This is my first time using wordpress, and nobody has explained the functions file to me completely right, but from my understanding, i don't do anything like do I?</p>
<p>I've also put <code><?php wp_footer(); ?></code> right before <code></body></code> if that means anything.</p>
<p>EDIT:
<strong>I've solved the problem</strong></p>
<p>Stupidly, I'd forgotten to add <code><?php wp_head(); ?></code> right before <code></head></code>, this screwed it all up. I also changed the 'main' identifier to something more unique, which didn't change anything but might be a better practice anyway.</p>
|
[
{
"answer_id": 206168,
"author": "Burgi",
"author_id": 62753,
"author_profile": "https://wordpress.stackexchange.com/users/62753",
"pm_score": 1,
"selected": false,
"text": "<p>The codex suggests using the function <code>get_stylesheet_directory()</code> in this instance as the <code>get_template_directory_uri()</code> can get overriden by child themes.</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri\" rel=\"nofollow\">get_template_directory_uri()</a></li>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory\" rel=\"nofollow\">get_stylesheet_directory()</a></li>\n</ul>\n\n<p>In my experience WordPress can sometimes provide 2 or 3 similar functions.</p>\n"
},
{
"answer_id": 206170,
"author": "csslove",
"author_id": 14087,
"author_profile": "https://wordpress.stackexchange.com/users/14087",
"pm_score": -1,
"selected": false,
"text": "<p>You should register js file. Please read WordPress codex</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_enqueue_script</a></p>\n"
}
] |
2015/10/21
|
[
"https://wordpress.stackexchange.com/questions/206167",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82293/"
] |
Ok, I've literally copy-pasted different enqueueing code from about 5 different sources (Including wordpress), and not a single one works.
Here's the code I'm using in functions.php:
```
<?php
function my_theme_scripts() {
wp_register_script(
'main',
get_stylesheet_directory_uri() . '/js/main.js',
array( 'jquery' ), '1.0.0', true
);
wp_enqueue_script('main');
}
add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );
?>
```
and it literally does nothing. No scripts added into my HTML. nothing.
This is my first time using wordpress, and nobody has explained the functions file to me completely right, but from my understanding, i don't do anything like do I?
I've also put `<?php wp_footer(); ?>` right before `</body>` if that means anything.
EDIT:
**I've solved the problem**
Stupidly, I'd forgotten to add `<?php wp_head(); ?>` right before `</head>`, this screwed it all up. I also changed the 'main' identifier to something more unique, which didn't change anything but might be a better practice anyway.
|
The codex suggests using the function `get_stylesheet_directory()` in this instance as the `get_template_directory_uri()` can get overriden by child themes.
* [get\_template\_directory\_uri()](https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri)
* [get\_stylesheet\_directory()](https://codex.wordpress.org/Function_Reference/get_stylesheet_directory)
In my experience WordPress can sometimes provide 2 or 3 similar functions.
|
206,184 |
<h2>How do I wrap a div around the actions in the code below?</h2>
<p>PHP in functions.php file:</p>
<pre><code>remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );
add_action( 'woocommerce_before_single_product_summary', 'woocommerce_template_single_title', 5 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 6 );
add_action( 'woocommerce_before_single_product_summary', 'woocommerce_template_single_price', 6 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 30 );
add_action( 'woocommerce_before_single_product_summary', 'woocommerce_template_single_excerpt', 10 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 6 );
add_action( 'woocommerce_before_single_product_summary', 'woocommerce_template_single_add_to_cart', 6 );
</code></pre>
<p><hr>
<strong>Question Background Info:</strong></p>
<p>I managed to move the title, price, excerpt, and add to cart before the images so that now I have the page set up as follows and it's what I want. But I want a div with the class "mobile-summary" around the first set.</p>
<pre><code><div class="new-div-i-want-to-add">
Title<br>
Price<br>
Add to Cart<br>
Excerpt<br>
</div>
<div class="images">Images</div>
<div class="summary">
Price<br>
Excerpt<br>
Add to Cart<br>
</div>
</code></pre>
<p><hr>
<strong>What have I tried?</strong></p>
<p>I don't know what it's called so nothing. I am learning Genesis and Woocommerce w/o much previous experience in php or Wordpress (even blogging as a user).</p>
|
[
{
"answer_id": 206185,
"author": "Gareth Gillman",
"author_id": 33936,
"author_profile": "https://wordpress.stackexchange.com/users/33936",
"pm_score": 1,
"selected": false,
"text": "<p>I would do it with jQuery, something like:</p>\n\n<pre><code>$('.element').wrapInner('<div class=\"mobile-summary\"></div>');\n</code></pre>\n\n<p>.element needs to be the div before where you want the code to work e.g.</p>\n\n<pre><code><div id=\"content>\n <div class=\"mobile-summary\">\n <img src=\"image.jpg\" />\n </div>\n</div>\n</code></pre>\n\n<p>Without a URL to work from it's hard to give a 100% answer but that will give you a starting point</p>\n"
},
{
"answer_id": 206203,
"author": "Christina",
"author_id": 64742,
"author_profile": "https://wordpress.stackexchange.com/users/64742",
"pm_score": 3,
"selected": true,
"text": "<p>I did the same thing a different way and now it's stacked like I want with a div wrapping the content. </p>\n\n<p>This stacks the single product woocommerce output to be as follows:</p>\n\n<ol>\n<li>Title</li>\n<li>Price</li>\n<li>Add to cart / attributes</li>\n<li>Excerpt</li>\n<li>Meta</li>\n<li>Images</li>\n<li>Price</li>\n<li>Add to cart / attributes</li>\n<li>Tabs</li>\n<li>Upsell</li>\n<li>Related</li>\n</ol>\n\n<p>So now on large viewports we float the .product div.images to the left, float the .product div.summary to the right, clear the stuff after it. Hide the .footer-cart-section on large viewports and now the person on a mobile phone won't have to scroll the the entire height of the image to add to cart - if they wish.</p>\n\n<p>In functions.php</p>\n\n<pre><code>if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {\n\n// ==== wrap in div\n function output_opening_div() {\n echo '<div class=\"footer-cart-section\">';\n }\n function ouput_closing_div() {\n echo '</div><!-- /.footer-cart-section -->';\n }\n\n// ==== put the excerpt below the add to cart and before the meta\n remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_excerpt',20);\n add_action('woocommerce_single_product_summary', 'woocommerce_template_single_excerpt',35);\n\n// ==== move images (with the thumbs) below the content\n remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20 );\n add_action( 'woocommerce_after_single_product_summary', 'woocommerce_show_product_images', 50);\n\n// ==== move all the content after images\n remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_product_data_tabs', 10 );\n remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_upsell_display', 15 );\n remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );\n\n add_action( 'woocommerce_after_single_product', 'woocommerce_output_product_data_tabs', 20);\n add_action( 'woocommerce_after_single_product', 'woocommerce_upsell_display', 20);\n add_action( 'woocommerce_after_single_product', 'woocommerce_output_related_products', 20 );\n\n// ==== repeat cart after image with opening and closing div functions\n\n add_action('woocommerce_after_single_product','output_opening_div',9);\n\n add_action( 'woocommerce_after_single_product', 'woocommerce_template_single_price', 10 );\n add_action( 'woocommerce_after_single_product', 'woocommerce_template_single_add_to_cart', 10 );\n\n add_action('woocommerce_after_single_product','ouput_closing_div',10);\n\n\n}// end if woocommerce\n</code></pre>\n"
}
] |
2015/10/21
|
[
"https://wordpress.stackexchange.com/questions/206184",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64742/"
] |
How do I wrap a div around the actions in the code below?
---------------------------------------------------------
PHP in functions.php file:
```
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );
add_action( 'woocommerce_before_single_product_summary', 'woocommerce_template_single_title', 5 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 6 );
add_action( 'woocommerce_before_single_product_summary', 'woocommerce_template_single_price', 6 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 30 );
add_action( 'woocommerce_before_single_product_summary', 'woocommerce_template_single_excerpt', 10 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 6 );
add_action( 'woocommerce_before_single_product_summary', 'woocommerce_template_single_add_to_cart', 6 );
```
---
**Question Background Info:**
I managed to move the title, price, excerpt, and add to cart before the images so that now I have the page set up as follows and it's what I want. But I want a div with the class "mobile-summary" around the first set.
```
<div class="new-div-i-want-to-add">
Title<br>
Price<br>
Add to Cart<br>
Excerpt<br>
</div>
<div class="images">Images</div>
<div class="summary">
Price<br>
Excerpt<br>
Add to Cart<br>
</div>
```
---
**What have I tried?**
I don't know what it's called so nothing. I am learning Genesis and Woocommerce w/o much previous experience in php or Wordpress (even blogging as a user).
|
I did the same thing a different way and now it's stacked like I want with a div wrapping the content.
This stacks the single product woocommerce output to be as follows:
1. Title
2. Price
3. Add to cart / attributes
4. Excerpt
5. Meta
6. Images
7. Price
8. Add to cart / attributes
9. Tabs
10. Upsell
11. Related
So now on large viewports we float the .product div.images to the left, float the .product div.summary to the right, clear the stuff after it. Hide the .footer-cart-section on large viewports and now the person on a mobile phone won't have to scroll the the entire height of the image to add to cart - if they wish.
In functions.php
```
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
// ==== wrap in div
function output_opening_div() {
echo '<div class="footer-cart-section">';
}
function ouput_closing_div() {
echo '</div><!-- /.footer-cart-section -->';
}
// ==== put the excerpt below the add to cart and before the meta
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_excerpt',20);
add_action('woocommerce_single_product_summary', 'woocommerce_template_single_excerpt',35);
// ==== move images (with the thumbs) below the content
remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20 );
add_action( 'woocommerce_after_single_product_summary', 'woocommerce_show_product_images', 50);
// ==== move all the content after images
remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_product_data_tabs', 10 );
remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_upsell_display', 15 );
remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );
add_action( 'woocommerce_after_single_product', 'woocommerce_output_product_data_tabs', 20);
add_action( 'woocommerce_after_single_product', 'woocommerce_upsell_display', 20);
add_action( 'woocommerce_after_single_product', 'woocommerce_output_related_products', 20 );
// ==== repeat cart after image with opening and closing div functions
add_action('woocommerce_after_single_product','output_opening_div',9);
add_action( 'woocommerce_after_single_product', 'woocommerce_template_single_price', 10 );
add_action( 'woocommerce_after_single_product', 'woocommerce_template_single_add_to_cart', 10 );
add_action('woocommerce_after_single_product','ouput_closing_div',10);
}// end if woocommerce
```
|
206,189 |
<p>When adding arrays to post meta, using add_post_meta, new sub-arrays are added. I was wondering if there was a way to have those sub-arrays named. </p>
<p>so instead of ending up with </p>
<pre><code>array([0](2,3), [1](4,5))
</code></pre>
<p>I would get</p>
<pre><code>array ([meaningful_name](2,3),[meaningful_name2](4,5))
</code></pre>
|
[
{
"answer_id": 206192,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 0,
"selected": false,
"text": "<p>Some possible ways for using add_post_meta : </p>\n\n<p><a href=\"http://worldpressrevolution.com/working-with-post-meta-arrays/\" rel=\"nofollow\">For details please follow link</a></p>\n\n<pre><code>add_post_meta($post_id, $meta_key, $meta_value, $unique);\nupdate_post_meta($post_id, $meta_key, $meta_value, $prev_value);\n$meta_values = get_post_meta( $post_id, $key, $single );\n\n\n\n update_post_meta($post_ID, {key}, {array of vals})\n\n $data = Array(\n 'url' => $url,\n 'name' => $name,\n 'description' => $desc,\n );\n\n //Update inserts a new entry if it doesn't exist, updates otherwise\n update_post_meta($post_ID, 'yourkey', $data);\n\n //To Fetch\n $yourdata = get_post_meta($post_ID, 'yourkey');\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/add_post_meta\" rel=\"nofollow\">Codex link for details</a></p>\n\n<p>Thanks!</p>\n"
},
{
"answer_id": 206198,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 4,
"selected": true,
"text": "<p>When multiple meta values are used for same meta key, WordPress store the values in different database rows. So every array, is stored in one row.</p>\n\n<h2>Initial Data</h2>\n\n<p>Let's assume you have an array like this:</p>\n\n<pre><code>$family = [\n 'father' => [ 'John', 'Doe', 40 ],\n 'mother' => [ 'Jane', 'White', 39 ],\n 'child_1' => [ 'Luke', 'Doe', 5 ]\n];\n</code></pre>\n\n<p>If you store each sub array as a different meta row, the only identifier for that row is the <code>meta_id</code> but it's not really meaningful and is hard to get using WordPress functions.</p>\n\n<h1>The <em>\"map\"</em> approach</h1>\n\n<p>A workaround could be to store a map of values / meta IDs in another post meta.</p>\n\n<p>That can be done thanks to the fact that both <code>update_post_meta()</code> and <code>add_post_meta()</code> return the meta ID just added.</p>\n\n<h3>Store Data</h3>\n\n<p>So you can do something like this:</p>\n\n<pre><code>$map = [];\nforeach( $family as $who => $person ) {\n // update_post_meta returns the meta ID\n $map[ $who ] = update_post_meta( $postId, 'family_member', $person );\n}\n// we store the map of family \"role\" to meta IDs in a separate meta\nupdate_post_meta( $postId, 'family_members_map', $map );\n</code></pre>\n\n<h3>Retrieve Data</h3>\n\n<p>When you retrieve values, e.g.</p>\n\n<pre><code>$family = get_post_meta( $postId, 'family_member' );\n</code></pre>\n\n<p>you get a 2 dimensions unkeyed array like this:</p>\n\n<pre><code>[\n [ 'John', 'Doe', 40 ],\n [ 'Jane', 'White', 39 ],\n [ 'Luke', 'Doe', 5 ],\n]\n</code></pre>\n\n<p>In short you loose the sub array keys.</p>\n\n<p>But you can use the map you stored and the function <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta_by_id/\" rel=\"nofollow\"><code>get_post_meta_by_id</code></a> to recreate your original data:</p>\n\n<pre><code>$map = get_post_meta( $postId, 'family_members_map', true );\n$family = array_combine( array_keys( $map ), array_map( 'get_post_meta_by_id', $map ) );\n</code></pre>\n\n<p>And family will be equal to the original data:</p>\n\n<pre><code>[\n 'father' => [ 'John Doe', 40 ],\n 'mother' => [ 'Jane White', 39 ],\n 'child_1' => [ 'Luke Doe', 5 ]\n]\n</code></pre>\n\n<h3>Update Data</h3>\n\n<p>Update data, it's not very hard:</p>\n\n<pre><code>$justBorn = [ 'Anna', 'Doe', 0 ];\n\n// current map\n$map = get_post_meta( $postId, 'family_members_map', true);\n\n// add both new sub array and new meta ID to map\n$map['child_2'] = update_post_meta( $postId, 'family_member', $justBorn );\n\n// update the map\nupdate_post_meta( $postId, 'family_members_map', $map );\n</code></pre>\n\n<h1>An alternative: the <em>\"all in one place\"</em> approach</h1>\n\n<p>The approach above works, but it's not the easiest way.</p>\n\n<p>In fact, would be easier to store the whole initial associative array (the <code>$family</code> array)\nis a single meta instead of in different sub-arrays.</p>\n\n<pre><code>// store data\nupdate_post_meta( $postId, 'family_members', $family );\n\n// retrieve data (please note the `true` as 3rd argument)\n$family = get_post_meta( $postId, 'family_members', true );\n\n// update data\n$family = get_post_meta( $postId, 'family_members', true );\n$family['child_2'] = [ 'Anna', 'Doe', 0 ];\nupdate_post_meta( $postId, 'family_members', $family );\n</code></pre>\n\n<p>To store, retrieve and update data is quite easy and there's no additional overhead.</p>\n\n<h1>Advantages of the <em>\"map\"</em> approach</h1>\n\n<p>In most of the cases, the <em>\"all in one place\"</em> approach is the most convenient.</p>\n\n<p>But if there are hundreds or even thousands of sub arrays, using an unique meta value to store them all would result in a very large amount of memory used to fetch and parse data.\nUsing different rows and a modern PHP feature like <a href=\"http://php.net/manual/en/language.generators.overview.php\" rel=\"nofollow\">generators</a>, that amount of memory can be <em>drastically</em> reduced.</p>\n\n<p>Moreover, when dealing with <em>existing</em> data (maybe inherited from old version of the website), this approach could be helpful to obtain meaningful information without conversion of old data.</p>\n\n<p>Finally, having smaller and more characterized sub arrays stored in different DB rows, a query for posts using meta query and <code>LIKE</code> against the serialized array in the meta value <em>could</em> be easier and more reliable, even if the actual reliability depends a lot on the structure of the data.</p>\n"
}
] |
2015/10/21
|
[
"https://wordpress.stackexchange.com/questions/206189",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/20014/"
] |
When adding arrays to post meta, using add\_post\_meta, new sub-arrays are added. I was wondering if there was a way to have those sub-arrays named.
so instead of ending up with
```
array([0](2,3), [1](4,5))
```
I would get
```
array ([meaningful_name](2,3),[meaningful_name2](4,5))
```
|
When multiple meta values are used for same meta key, WordPress store the values in different database rows. So every array, is stored in one row.
Initial Data
------------
Let's assume you have an array like this:
```
$family = [
'father' => [ 'John', 'Doe', 40 ],
'mother' => [ 'Jane', 'White', 39 ],
'child_1' => [ 'Luke', 'Doe', 5 ]
];
```
If you store each sub array as a different meta row, the only identifier for that row is the `meta_id` but it's not really meaningful and is hard to get using WordPress functions.
The *"map"* approach
====================
A workaround could be to store a map of values / meta IDs in another post meta.
That can be done thanks to the fact that both `update_post_meta()` and `add_post_meta()` return the meta ID just added.
### Store Data
So you can do something like this:
```
$map = [];
foreach( $family as $who => $person ) {
// update_post_meta returns the meta ID
$map[ $who ] = update_post_meta( $postId, 'family_member', $person );
}
// we store the map of family "role" to meta IDs in a separate meta
update_post_meta( $postId, 'family_members_map', $map );
```
### Retrieve Data
When you retrieve values, e.g.
```
$family = get_post_meta( $postId, 'family_member' );
```
you get a 2 dimensions unkeyed array like this:
```
[
[ 'John', 'Doe', 40 ],
[ 'Jane', 'White', 39 ],
[ 'Luke', 'Doe', 5 ],
]
```
In short you loose the sub array keys.
But you can use the map you stored and the function [`get_post_meta_by_id`](https://developer.wordpress.org/reference/functions/get_post_meta_by_id/) to recreate your original data:
```
$map = get_post_meta( $postId, 'family_members_map', true );
$family = array_combine( array_keys( $map ), array_map( 'get_post_meta_by_id', $map ) );
```
And family will be equal to the original data:
```
[
'father' => [ 'John Doe', 40 ],
'mother' => [ 'Jane White', 39 ],
'child_1' => [ 'Luke Doe', 5 ]
]
```
### Update Data
Update data, it's not very hard:
```
$justBorn = [ 'Anna', 'Doe', 0 ];
// current map
$map = get_post_meta( $postId, 'family_members_map', true);
// add both new sub array and new meta ID to map
$map['child_2'] = update_post_meta( $postId, 'family_member', $justBorn );
// update the map
update_post_meta( $postId, 'family_members_map', $map );
```
An alternative: the *"all in one place"* approach
=================================================
The approach above works, but it's not the easiest way.
In fact, would be easier to store the whole initial associative array (the `$family` array)
is a single meta instead of in different sub-arrays.
```
// store data
update_post_meta( $postId, 'family_members', $family );
// retrieve data (please note the `true` as 3rd argument)
$family = get_post_meta( $postId, 'family_members', true );
// update data
$family = get_post_meta( $postId, 'family_members', true );
$family['child_2'] = [ 'Anna', 'Doe', 0 ];
update_post_meta( $postId, 'family_members', $family );
```
To store, retrieve and update data is quite easy and there's no additional overhead.
Advantages of the *"map"* approach
==================================
In most of the cases, the *"all in one place"* approach is the most convenient.
But if there are hundreds or even thousands of sub arrays, using an unique meta value to store them all would result in a very large amount of memory used to fetch and parse data.
Using different rows and a modern PHP feature like [generators](http://php.net/manual/en/language.generators.overview.php), that amount of memory can be *drastically* reduced.
Moreover, when dealing with *existing* data (maybe inherited from old version of the website), this approach could be helpful to obtain meaningful information without conversion of old data.
Finally, having smaller and more characterized sub arrays stored in different DB rows, a query for posts using meta query and `LIKE` against the serialized array in the meta value *could* be easier and more reliable, even if the actual reliability depends a lot on the structure of the data.
|
206,197 |
<p>I have a custom query:</p>
<pre><code><?php
query_posts(array(
'post_type' => 'properties',
'meta_key' => 'pd_city',
'orderby' => 'meta_value',
'order' => 'ASC',
'posts_per_page' => 5,
'paged' => get_query_var('paged')
));
?>
</code></pre>
<p>But it doesn't seem to be working. The posts on this page should be listed alphabetically by city (Burnaby, New Westminster, Richmond, Surrey), but they are listed in a random order (I'm not sure how they are being ordered).</p>
<p>Not sure what I'm missing. I created the 'properties' post_type via the 'Post Meta' Wordpress plugin if that makes a difference.</p>
<p><a href="http://www.professionalrentals.ca/new-properties-test-page/" rel="nofollow">http://www.professionalrentals.ca/new-properties-test-page/</a></p>
<hr>
<p>Attempt using WP_Query - Also <strong>DOES NOT WORK</strong></p>
<pre><code><?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'properties',
'meta_key' => 'pd_city',
'orderby' => 'meta_value',
'order' => 'ASC',
'posts_per_page' => 5,
'paged' => $paged
);
$the_query = new WP_Query( $args );
?>
<?php if ($the_query->have_posts()) : while ($the_query->have_posts()) : $the_query->the_post(); ?>
</code></pre>
|
[
{
"answer_id": 206204,
"author": "darrinb",
"author_id": 6304,
"author_profile": "https://wordpress.stackexchange.com/users/6304",
"pm_score": 2,
"selected": false,
"text": "<p>Piter is right, don't use <code>query_posts</code>. </p>\n\n<p>You could do something like:</p>\n\n<pre><code>$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;\n$args = array(\n 'post_type' => 'properties',\n 'meta_key' => 'pd_city',\n 'orderby' => 'meta_value',\n 'order' => 'ASC',\n 'posts_per_page' => 5,\n 'paged' => $paged\n);\n\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>Just make sure you have the values right for your <code>post_type</code> and <code>meta_key</code> params. I.e, I use an underscore for all my meta keys: <code>_properties</code>.</p>\n\n<p>I have a nearly identical query running on a client's project here: <a href=\"http://centerpoint.com/properties/?pgd=1&v=list&filter=1&list_type=all&sortby=city\" rel=\"nofollow\">http://centerpoint.com/properties/?pgd=1&v=list&filter=1&list_type=all&sortby=city</a></p>\n"
},
{
"answer_id": 206215,
"author": "vancoder",
"author_id": 26778,
"author_profile": "https://wordpress.stackexchange.com/users/26778",
"pm_score": 0,
"selected": false,
"text": "<p>I took a quick look at the Post Meta plugin you are using, and it appears to save it's meta values as serialized arrays. Therefore your query is never going to work - WP doesn't know how to order a bunch of serialized arrays.</p>\n\n<p>If you really want to use a plug-in (rather than build your own meta fields), I'd recommend you dump Post Meta and switch to <a href=\"https://wordpress.org/plugins/advanced-custom-fields/\" rel=\"nofollow\">Advanced Custom Fields</a>. Note you'll need to deactivate Post Meta for ACF to work.</p>\n"
},
{
"answer_id": 206302,
"author": "KVDD",
"author_id": 54304,
"author_profile": "https://wordpress.stackexchange.com/users/54304",
"pm_score": 0,
"selected": false,
"text": "<p>Okay I have a really ridiculous work around that ends up running the query multiple times (I'm sure I'll get torn apart in the comments for this), but it works for now so here goes. </p>\n\n<p>This only works if you know exactly which fields you will be sorting between. AKA I have a list of cities I need ordered alphabetically. And I know there are only these cities.\n<em>(I guess you could run a separate query to get this array from the DB but I didn't want MORE queries)</em></p>\n\n<pre><code><?php\n$listOfCities = array('burnaby', 'delta', 'ladner', 'new westminster', 'north vancouver', 'richmond', 'tsawwassen', 'vancouver', 'white rock');\n\nforeach ($listOfCities as $cities) {\n\n$args = array(\n'post_type' => 'properties',\n'meta_key' => 'pd_city',\n'meta_query' => array(\n array(\n 'key' => 'pd_city',\n 'value' => $cities,\n 'compare' => 'LIKE'\n )),\n'order' => 'ASC'\n);\n$the_query = new WP_Query( $args );\n\nif ($the_query->have_posts()) : while ($the_query->have_posts()) : $the_query->the_post();\n\n echo get_field(pd_city);\n\nendwhile; endif; wp_reset_postdata();\n\n}\n?>\n</code></pre>\n\n<p>And after all that the client wanted it ordered a different way, but since it processes it based on what's first in the array to last, I just changed the array to:</p>\n\n<pre><code>$listOfCities = array('vancouver', 'richmond', 'burnaby', 'new westminster', 'north vancouver', 'white rock', 'delta', 'ladner', 'tsawwassen');\n</code></pre>\n"
}
] |
2015/10/21
|
[
"https://wordpress.stackexchange.com/questions/206197",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54304/"
] |
I have a custom query:
```
<?php
query_posts(array(
'post_type' => 'properties',
'meta_key' => 'pd_city',
'orderby' => 'meta_value',
'order' => 'ASC',
'posts_per_page' => 5,
'paged' => get_query_var('paged')
));
?>
```
But it doesn't seem to be working. The posts on this page should be listed alphabetically by city (Burnaby, New Westminster, Richmond, Surrey), but they are listed in a random order (I'm not sure how they are being ordered).
Not sure what I'm missing. I created the 'properties' post\_type via the 'Post Meta' Wordpress plugin if that makes a difference.
<http://www.professionalrentals.ca/new-properties-test-page/>
---
Attempt using WP\_Query - Also **DOES NOT WORK**
```
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'properties',
'meta_key' => 'pd_city',
'orderby' => 'meta_value',
'order' => 'ASC',
'posts_per_page' => 5,
'paged' => $paged
);
$the_query = new WP_Query( $args );
?>
<?php if ($the_query->have_posts()) : while ($the_query->have_posts()) : $the_query->the_post(); ?>
```
|
Piter is right, don't use `query_posts`.
You could do something like:
```
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'properties',
'meta_key' => 'pd_city',
'orderby' => 'meta_value',
'order' => 'ASC',
'posts_per_page' => 5,
'paged' => $paged
);
$query = new WP_Query( $args );
```
Just make sure you have the values right for your `post_type` and `meta_key` params. I.e, I use an underscore for all my meta keys: `_properties`.
I have a nearly identical query running on a client's project here: <http://centerpoint.com/properties/?pgd=1&v=list&filter=1&list_type=all&sortby=city>
|
206,208 |
<p>I am using Advanced Custom Fields to get a list of properties as follows:-</p>
<pre><code> <?php
$args = array(
'posts_per_page'=> -1,
'post_type' => 'properties',
'meta_key' => 'development',
'meta_value' => $development_id
);
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="col-md-4">
<?php the_title(); ?>
<?php the_field('price'); ?>
Plot <?php the_field('plot_no'); ?>
</div>
<?php endwhile; ?>
<?php endif; wp_reset_query(); ?>
</code></pre>
<p>The following; <code><?php the_field('price'); ?>β</code> returns:-</p>
<p><code>325000 489950 329000 325000 294995 199950 294995 252950 325000 257950 197950 325000</code></p>
<p>What I need is to get the lowest and highest value as a variable, any ideas how I would do this?</p>
|
[
{
"answer_id": 206213,
"author": "darrinb",
"author_id": 6304,
"author_profile": "https://wordpress.stackexchange.com/users/6304",
"pm_score": 0,
"selected": false,
"text": "<p>Without knowing whether returns a single value, an array, or a string of values separated by spaces, I'd suggest something like:</p>\n\n<pre><code><?php\n$args = array(\n 'posts_per_page'=> -1,\n 'post_type' => 'properties',\n 'meta_key' => 'development',\n 'meta_value' => $development_id\n);\n$the_query = new WP_Query( $args ); \n\n?>\n<?php if( $the_query->have_posts() ): ?>\n<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>\n <?php $min_price = $max_price = ''; ?>\n <div class=\"col-md-4\">\n <?php the_title(); ?>\n <?php \n $price = get_the_field('price'); \n if( $price ) {\n // if it's an array already:\n $min_price = min($price);\n $max_price = max($price);\n\n // if it's not an array already:\n $prices = explode(' ', $price);\n $min_price = min($prices);\n $max_price = max($prices); \n }\n ?>\n <?php the_field('price'); ?>\n Plot <?php the_field('plot_no'); ?>\n </div>\n<?php endwhile; ?>\n<?php endif; wp_reset_query(); ?> \n</code></pre>\n"
},
{
"answer_id": 206246,
"author": "nsilva",
"author_id": 81966,
"author_profile": "https://wordpress.stackexchange.com/users/81966",
"pm_score": 3,
"selected": true,
"text": "<p>Got it working in the end with the below code:</p>\n\n<pre><code> <?php\n $args = array(\n 'posts_per_page'=> -1,\n 'post_type' => 'properties',\n 'meta_key' => 'development',\n 'meta_value' => $development_id,\n );\n $properties_query = new WP_Query( $args ); \n $prices = array();\n\n if( $properties_query->have_posts() ):\n while( $properties_query->have_posts() ) : $properties_query->the_post();\n $price = get_field('price'); \n if(isset($price) && !empty($price)){\n $prices[] = $price; \n }\n endwhile;\n $max_price = max($prices);\n $min_price = min($prices);\n\n endif; wp_reset_query(); \n ?>\n</code></pre>\n"
}
] |
2015/10/21
|
[
"https://wordpress.stackexchange.com/questions/206208",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81966/"
] |
I am using Advanced Custom Fields to get a list of properties as follows:-
```
<?php
$args = array(
'posts_per_page'=> -1,
'post_type' => 'properties',
'meta_key' => 'development',
'meta_value' => $development_id
);
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="col-md-4">
<?php the_title(); ?>
<?php the_field('price'); ?>
Plot <?php the_field('plot_no'); ?>
</div>
<?php endwhile; ?>
<?php endif; wp_reset_query(); ?>
```
The following; `<?php the_field('price'); ?>β` returns:-
`325000 489950 329000 325000 294995 199950 294995 252950 325000 257950 197950 325000`
What I need is to get the lowest and highest value as a variable, any ideas how I would do this?
|
Got it working in the end with the below code:
```
<?php
$args = array(
'posts_per_page'=> -1,
'post_type' => 'properties',
'meta_key' => 'development',
'meta_value' => $development_id,
);
$properties_query = new WP_Query( $args );
$prices = array();
if( $properties_query->have_posts() ):
while( $properties_query->have_posts() ) : $properties_query->the_post();
$price = get_field('price');
if(isset($price) && !empty($price)){
$prices[] = $price;
}
endwhile;
$max_price = max($prices);
$min_price = min($prices);
endif; wp_reset_query();
?>
```
|
206,235 |
<p>I have following args to get recent posts,</p>
<pre><code>$args = array(
'date_query' => array( array( 'after' => '1 week ago' ) ),
'posts_per_page' => 15,
'ignore_sticky_posts' => 1,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'cat' => '-907,-908,-909'
);
</code></pre>
<p>Now I need include few specific Ids to same query. So I tried follows, but it doesn't work</p>
<pre><code>$highlights = array('8308', '8315');
$args = array(
'date_query' => array( array( 'after' => '1 week ago' ) ),
'posts_per_page' => 15,
'ignore_sticky_posts' => 1,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'cat' => '-907,-908,-909',
'post__in' => $highlights
);
</code></pre>
<p>Now it just giving me those two posts.</p>
|
[
{
"answer_id": 206242,
"author": "Janith Chinthana",
"author_id": 68403,
"author_profile": "https://wordpress.stackexchange.com/users/68403",
"pm_score": 2,
"selected": false,
"text": "<p>I am not sure, is this the best way, but I succeed with following code.</p>\n\n<pre><code>$highlights = array('8308', '8315');\n\n$args1 = array(\n 'post__in' => $highlights\n);\n\n$args2 = array(\n 'date_query' => array( array( 'after' => '1 week ago' ) ), \n 'posts_per_page' => 13,\n 'ignore_sticky_posts' => 1,\n 'meta_key' => 'post_views_count',\n 'orderby' => 'meta_value_num',\n 'order' => 'DESC',\n 'cat' => '-907,-908,-909',\n 'post__not_in' => $highlights\n);\n\n$query1 = new WP_Query($args1);\n$query2 = new WP_Query($args2);\n\n$products = new WP_Query();\n$products->posts = array_merge( $query1->posts, $query2->posts );\n$products->post_count = $query1->post_count + $query2->post_count;\n</code></pre>\n\n<p><code>$products</code> is the final post array.</p>\n"
},
{
"answer_id": 206250,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>Here is another way of doing it, specially if you need to work with the query object. The issue with merging queries is that you loose the correctness of the query object.</p>\n\n<p>My idea here is to run two separate queries, one very lean one to get post ID's from the <code>date_query</code> query and then merging the two arrays of post ID's and then pass those ID's to proper <code>WP_Query</code> query. </p>\n\n<p>(<em>NOTE: This code requires at least PHP 5.4</em>)</p>\n\n<pre><code>$highlights = [8308, 8315];\n\n$args = [\n 'date_query' => [\n [\n 'after' => '1 week ago' \n ]\n ],\n 'posts_per_page' => 13,\n 'meta_key' => 'post_views_count',\n 'orderby' => 'meta_value_num',\n 'order' => 'DESC',\n 'cat' => '-907,-908,-909',\n 'post__not_in' => $highlights,\n 'fields' => 'ids' // ONLY GET POST ID's, VERY LEAN QUERY\n];\n$q = get_posts( $args );\n\n$merged_ids = array_merge( $highlights, $q );\n</code></pre>\n\n<p>Note now, the hightlights are in front of the query, and the posts from $q is ordered by date. If you need to retain this order, simply add <code>'orderby' => 'post__in',</code> to the arguments of the query below</p>\n\n<pre><code>if ( $merged_ids ) {\n $args_final = [\n 'post__in' => $merged_ids,\n 'posts_per_page' => -1,\n 'orderby' => 'post__in',\n 'ignore_sticky_posts' => 1\n ];\n $query_final = new WP_Query( $args_final );\n\n // Run your loop\n}\n</code></pre>\n"
},
{
"answer_id": 381731,
"author": "samjco",
"author_id": 29133,
"author_profile": "https://wordpress.stackexchange.com/users/29133",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, I've found this solution to be very versatile:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$highlights = array('8308', '8315');\n \n//Optionally, to get these IDS (or others, maybe of the different posttype, or whatever) you can use a simple args with get_posts function and return just the ids using the arg fields => ids\n\n\n$args2 = array(\n 'date_query' => array( array( 'after' => '1 week ago' ) ), \n 'posts_per_page' => 13, //<-- Make sure to enter the max (total) amount for both\n 'ignore_sticky_posts' => 1,\n 'meta_key' => 'post_views_count',\n 'orderby' => 'meta_value_num',\n 'order' => 'DESC', //<-- this is disabled, because we will enable later\n 'cat' => '-907,-908,-909',\n 'fields' => 'ids' // Returns nothing but IDs\n);\n\n $args2 = get_posts($args2); //returns IDs \n\n $merged_args = array_merge( $args2, $highlights); //Let's merge the IDS..\n $merged_args = array_unique( $merged_args ); // get only uniques... \n\n\n $firstQuery= new WP_Query( array(\n 'post__in' => $merged_args, \n 'posts_per_page' => 2, // Only return 2 post out of the MAX of 13\n 'ignore_sticky_posts' => true, \n 'orderby' => 'date' \n ) \n );\n\n\nif ($firstQuery->have_posts()) : // The Loop\n$firstQuery_count= 0;\n\n while ($firstQuery->have_posts()): $firstQuery->the_post();\n $firstQuery_count++;\n\n //Do something here with firstQuery....\n\n endwhile;\n wp_reset_query();\n\nendif;\n\n $secondQuery= new WP_Query( array(\n 'post__in' => $merged_args, \n 'offset' => 2, // do not forget to add an offset of the 2 from the firstQuery\n 'posts_per_page' => 11, // Only return 11 post out of the MAX of 13\n 'ignore_sticky_posts' => true, \n 'orderby' => 'date' \n ) \n );\n\n\nif ($secondQuery->have_posts()) : // The Loop\n$secondQuery_count= 0;\n\n while ($secondQuery->have_posts()): $secondQuery->the_post();\n $secondQuery_count++;\n\n //Do something here with secondQuery....\n\n endwhile;\n wp_reset_query();\n\nendif;\n</code></pre>\n"
}
] |
2015/10/22
|
[
"https://wordpress.stackexchange.com/questions/206235",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68403/"
] |
I have following args to get recent posts,
```
$args = array(
'date_query' => array( array( 'after' => '1 week ago' ) ),
'posts_per_page' => 15,
'ignore_sticky_posts' => 1,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'cat' => '-907,-908,-909'
);
```
Now I need include few specific Ids to same query. So I tried follows, but it doesn't work
```
$highlights = array('8308', '8315');
$args = array(
'date_query' => array( array( 'after' => '1 week ago' ) ),
'posts_per_page' => 15,
'ignore_sticky_posts' => 1,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'cat' => '-907,-908,-909',
'post__in' => $highlights
);
```
Now it just giving me those two posts.
|
Here is another way of doing it, specially if you need to work with the query object. The issue with merging queries is that you loose the correctness of the query object.
My idea here is to run two separate queries, one very lean one to get post ID's from the `date_query` query and then merging the two arrays of post ID's and then pass those ID's to proper `WP_Query` query.
(*NOTE: This code requires at least PHP 5.4*)
```
$highlights = [8308, 8315];
$args = [
'date_query' => [
[
'after' => '1 week ago'
]
],
'posts_per_page' => 13,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'cat' => '-907,-908,-909',
'post__not_in' => $highlights,
'fields' => 'ids' // ONLY GET POST ID's, VERY LEAN QUERY
];
$q = get_posts( $args );
$merged_ids = array_merge( $highlights, $q );
```
Note now, the hightlights are in front of the query, and the posts from $q is ordered by date. If you need to retain this order, simply add `'orderby' => 'post__in',` to the arguments of the query below
```
if ( $merged_ids ) {
$args_final = [
'post__in' => $merged_ids,
'posts_per_page' => -1,
'orderby' => 'post__in',
'ignore_sticky_posts' => 1
];
$query_final = new WP_Query( $args_final );
// Run your loop
}
```
|
206,251 |
<p>I want to sort the result of <code>get_users()</code> by last name, first name, user defined fields or whatever. </p>
<p>How can I achieve this while still using <code>get_users()</code>?</p>
|
[
{
"answer_id": 206252,
"author": "flomei",
"author_id": 65455,
"author_profile": "https://wordpress.stackexchange.com/users/65455",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/get_users\" rel=\"noreferrer\"><code>get_users()</code></a> does not allow you to directly sort by whatever you like, but there are ways around it.</p>\n\n<p>The Codex for <code>get_users()</code> says:</p>\n\n<blockquote>\n <p><strong>orderby</strong> - Sort by 'ID', 'login', 'nicename', 'email', 'url', 'registered', 'display_name', 'post_count', 'include', or 'meta_value' (query must also contain a 'meta_key' - see <a href=\"https://codex.wordpress.org/Class_Reference/WP_User_Query\" rel=\"noreferrer\">WP_User_Query</a>).</p>\n</blockquote>\n\n<p><code>meta_value</code> is a very powerful way to go here. If you choose it, you have to define the <code>meta_key</code> which will then define what to order by.</p>\n\n<blockquote>\n <p><strong>meta_key</strong> - The <strong>meta_key</strong> in the <a href=\"https://codex.wordpress.org/Database_Description#Table:_wp_usermeta\" rel=\"noreferrer\">wp_usermeta table</a> for the <strong>meta_value</strong> to be returned. See <a href=\"https://codex.wordpress.org/Function_Reference/get_userdata#Values_in_users_.26_user_meta_table\" rel=\"noreferrer\">get_userdata()</a> for the possible meta keys.</p>\n</blockquote>\n\n<p><code>get_userdata()</code> can <a href=\"https://codex.wordpress.org/Function_Reference/get_userdata#Notes\" rel=\"noreferrer\">return quite a lot of values,</a> possibly enough to order by.</p>\n\n<hr>\n\n<p><strong>Examples</strong></p>\n\n<p>So, if you want to order by the users last name for example, use <code>get_users()</code> like this:</p>\n\n<pre><code>$your_users = get_users('orderby=meta_value&meta_key=last_name');\n</code></pre>\n\n<p>Order by first name</p>\n\n<pre><code>$your_users = get_users('orderby=meta_value&meta_key=first_name');\n</code></pre>\n\n<p>Order by registration date</p>\n\n<pre><code>$your_users = get_users('orderby=meta_value&meta_key=user_registered');\n</code></pre>\n\n<p>You can of course use <code>order</code> to reverse the sorting order</p>\n\n<pre><code>// Sorting users by registration date - ascending (standard behaviour)\n$your_users = get_users('orderby=meta_value&meta_key=user_registered');\n// Sorting users by registration date - descending (add order=DESC)\n$your_users = get_users('orderby=meta_value&meta_key=user_registered&order=DESC');\n</code></pre>\n\n<hr>\n\n<p><strong>One step further</strong></p>\n\n<p>If you want to order by user-defined values, which <code>get_userdata()</code> wonΒ΄t deliver, you can pass another parameter to <code>get_users()</code>.</p>\n\n<pre><code>$your_users = get_users('fields=all_with_meta');\n</code></pre>\n\n<p>This will result in an array which contains all meta data that is linked to a user. You can then use a custom sort function (<a href=\"https://secure.php.net/manual/function.usort.php\" rel=\"noreferrer\">via usort()</a>) to order by a specific parameter.</p>\n\n<pre><code>$your_users = get_users('fields=all_with_meta');\n// very basic comparison...\nfunction compare($a, $b) { return ($a->special > $b->special) ? -1 : 1; }\nusort($your_users, 'compare');\n</code></pre>\n"
},
{
"answer_id": 403530,
"author": "Zoroaster",
"author_id": 220083,
"author_profile": "https://wordpress.stackexchange.com/users/220083",
"pm_score": 1,
"selected": false,
"text": "<p>As for the examples:\nthe mentioned <code>$your_users = get_users('orderby=meta_value&meta_key=user_registered');</code> will not work, since user_registered is NOT in user_meta table (therefore no <code>meta_key</code> and no <code>meta_value</code>) but is in (core) users table, so\n<code>get_users('orderby=user_registered')</code> will do the job.</p>\n"
}
] |
2015/10/22
|
[
"https://wordpress.stackexchange.com/questions/206251",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65455/"
] |
I want to sort the result of `get_users()` by last name, first name, user defined fields or whatever.
How can I achieve this while still using `get_users()`?
|
[`get_users()`](https://codex.wordpress.org/Function_Reference/get_users) does not allow you to directly sort by whatever you like, but there are ways around it.
The Codex for `get_users()` says:
>
> **orderby** - Sort by 'ID', 'login', 'nicename', 'email', 'url', 'registered', 'display\_name', 'post\_count', 'include', or 'meta\_value' (query must also contain a 'meta\_key' - see [WP\_User\_Query](https://codex.wordpress.org/Class_Reference/WP_User_Query)).
>
>
>
`meta_value` is a very powerful way to go here. If you choose it, you have to define the `meta_key` which will then define what to order by.
>
> **meta\_key** - The **meta\_key** in the [wp\_usermeta table](https://codex.wordpress.org/Database_Description#Table:_wp_usermeta) for the **meta\_value** to be returned. See [get\_userdata()](https://codex.wordpress.org/Function_Reference/get_userdata#Values_in_users_.26_user_meta_table) for the possible meta keys.
>
>
>
`get_userdata()` can [return quite a lot of values,](https://codex.wordpress.org/Function_Reference/get_userdata#Notes) possibly enough to order by.
---
**Examples**
So, if you want to order by the users last name for example, use `get_users()` like this:
```
$your_users = get_users('orderby=meta_value&meta_key=last_name');
```
Order by first name
```
$your_users = get_users('orderby=meta_value&meta_key=first_name');
```
Order by registration date
```
$your_users = get_users('orderby=meta_value&meta_key=user_registered');
```
You can of course use `order` to reverse the sorting order
```
// Sorting users by registration date - ascending (standard behaviour)
$your_users = get_users('orderby=meta_value&meta_key=user_registered');
// Sorting users by registration date - descending (add order=DESC)
$your_users = get_users('orderby=meta_value&meta_key=user_registered&order=DESC');
```
---
**One step further**
If you want to order by user-defined values, which `get_userdata()` wonΒ΄t deliver, you can pass another parameter to `get_users()`.
```
$your_users = get_users('fields=all_with_meta');
```
This will result in an array which contains all meta data that is linked to a user. You can then use a custom sort function ([via usort()](https://secure.php.net/manual/function.usort.php)) to order by a specific parameter.
```
$your_users = get_users('fields=all_with_meta');
// very basic comparison...
function compare($a, $b) { return ($a->special > $b->special) ? -1 : 1; }
usort($your_users, 'compare');
```
|
206,285 |
<p>I would like to use something to filter images within an ACF Gallery. I have added the Enhanced Media Gallery Plugin which will allow me to assign a category to each image, but am not not clear on how to echo out that category list so it can be clicked and filter/display images in the category chosen. </p>
<p>Additionally, how would I echo the category assigned to the image in the div surrounding the image </p>
<p>My loop currently looks like this to output my gallery. </p>
<p>I would be grateful for any advice on the best way to assign categories to each image in my gallery (is a plugin best here?) and also how to grab those categories and sort. Thanks in Advance! </p>
<pre><code><div class="wrapper-gallery" itemscope itemtype="http://schema.org/ImageGallery">
<?php
$images = get_field('images');
if( $images ): ?>
<?php foreach( $images as $image ): ?>
<div class="gallery-image" id="imageGallery">
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="<?php echo $image['url']; ?>" itemprop="contentUrl" data-size="<?php echo $image['width'] . 'x' . $image['height']; ?>">
<img src="<?php echo $image['sizes']['large']; ?>" itemprop="thumbnail" alt="<?php echo $image['alt']; ?>" />
</a>
<figcaption itemprop="caption description"><?php echo $image['caption']; ?></figcaption>
</figure>
</div>
<?php endforeach; ?>
<?php endif; ?>
</code></pre>
|
[
{
"answer_id": 206252,
"author": "flomei",
"author_id": 65455,
"author_profile": "https://wordpress.stackexchange.com/users/65455",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/get_users\" rel=\"noreferrer\"><code>get_users()</code></a> does not allow you to directly sort by whatever you like, but there are ways around it.</p>\n\n<p>The Codex for <code>get_users()</code> says:</p>\n\n<blockquote>\n <p><strong>orderby</strong> - Sort by 'ID', 'login', 'nicename', 'email', 'url', 'registered', 'display_name', 'post_count', 'include', or 'meta_value' (query must also contain a 'meta_key' - see <a href=\"https://codex.wordpress.org/Class_Reference/WP_User_Query\" rel=\"noreferrer\">WP_User_Query</a>).</p>\n</blockquote>\n\n<p><code>meta_value</code> is a very powerful way to go here. If you choose it, you have to define the <code>meta_key</code> which will then define what to order by.</p>\n\n<blockquote>\n <p><strong>meta_key</strong> - The <strong>meta_key</strong> in the <a href=\"https://codex.wordpress.org/Database_Description#Table:_wp_usermeta\" rel=\"noreferrer\">wp_usermeta table</a> for the <strong>meta_value</strong> to be returned. See <a href=\"https://codex.wordpress.org/Function_Reference/get_userdata#Values_in_users_.26_user_meta_table\" rel=\"noreferrer\">get_userdata()</a> for the possible meta keys.</p>\n</blockquote>\n\n<p><code>get_userdata()</code> can <a href=\"https://codex.wordpress.org/Function_Reference/get_userdata#Notes\" rel=\"noreferrer\">return quite a lot of values,</a> possibly enough to order by.</p>\n\n<hr>\n\n<p><strong>Examples</strong></p>\n\n<p>So, if you want to order by the users last name for example, use <code>get_users()</code> like this:</p>\n\n<pre><code>$your_users = get_users('orderby=meta_value&meta_key=last_name');\n</code></pre>\n\n<p>Order by first name</p>\n\n<pre><code>$your_users = get_users('orderby=meta_value&meta_key=first_name');\n</code></pre>\n\n<p>Order by registration date</p>\n\n<pre><code>$your_users = get_users('orderby=meta_value&meta_key=user_registered');\n</code></pre>\n\n<p>You can of course use <code>order</code> to reverse the sorting order</p>\n\n<pre><code>// Sorting users by registration date - ascending (standard behaviour)\n$your_users = get_users('orderby=meta_value&meta_key=user_registered');\n// Sorting users by registration date - descending (add order=DESC)\n$your_users = get_users('orderby=meta_value&meta_key=user_registered&order=DESC');\n</code></pre>\n\n<hr>\n\n<p><strong>One step further</strong></p>\n\n<p>If you want to order by user-defined values, which <code>get_userdata()</code> wonΒ΄t deliver, you can pass another parameter to <code>get_users()</code>.</p>\n\n<pre><code>$your_users = get_users('fields=all_with_meta');\n</code></pre>\n\n<p>This will result in an array which contains all meta data that is linked to a user. You can then use a custom sort function (<a href=\"https://secure.php.net/manual/function.usort.php\" rel=\"noreferrer\">via usort()</a>) to order by a specific parameter.</p>\n\n<pre><code>$your_users = get_users('fields=all_with_meta');\n// very basic comparison...\nfunction compare($a, $b) { return ($a->special > $b->special) ? -1 : 1; }\nusort($your_users, 'compare');\n</code></pre>\n"
},
{
"answer_id": 403530,
"author": "Zoroaster",
"author_id": 220083,
"author_profile": "https://wordpress.stackexchange.com/users/220083",
"pm_score": 1,
"selected": false,
"text": "<p>As for the examples:\nthe mentioned <code>$your_users = get_users('orderby=meta_value&meta_key=user_registered');</code> will not work, since user_registered is NOT in user_meta table (therefore no <code>meta_key</code> and no <code>meta_value</code>) but is in (core) users table, so\n<code>get_users('orderby=user_registered')</code> will do the job.</p>\n"
}
] |
2015/10/22
|
[
"https://wordpress.stackexchange.com/questions/206285",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81981/"
] |
I would like to use something to filter images within an ACF Gallery. I have added the Enhanced Media Gallery Plugin which will allow me to assign a category to each image, but am not not clear on how to echo out that category list so it can be clicked and filter/display images in the category chosen.
Additionally, how would I echo the category assigned to the image in the div surrounding the image
My loop currently looks like this to output my gallery.
I would be grateful for any advice on the best way to assign categories to each image in my gallery (is a plugin best here?) and also how to grab those categories and sort. Thanks in Advance!
```
<div class="wrapper-gallery" itemscope itemtype="http://schema.org/ImageGallery">
<?php
$images = get_field('images');
if( $images ): ?>
<?php foreach( $images as $image ): ?>
<div class="gallery-image" id="imageGallery">
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="<?php echo $image['url']; ?>" itemprop="contentUrl" data-size="<?php echo $image['width'] . 'x' . $image['height']; ?>">
<img src="<?php echo $image['sizes']['large']; ?>" itemprop="thumbnail" alt="<?php echo $image['alt']; ?>" />
</a>
<figcaption itemprop="caption description"><?php echo $image['caption']; ?></figcaption>
</figure>
</div>
<?php endforeach; ?>
<?php endif; ?>
```
|
[`get_users()`](https://codex.wordpress.org/Function_Reference/get_users) does not allow you to directly sort by whatever you like, but there are ways around it.
The Codex for `get_users()` says:
>
> **orderby** - Sort by 'ID', 'login', 'nicename', 'email', 'url', 'registered', 'display\_name', 'post\_count', 'include', or 'meta\_value' (query must also contain a 'meta\_key' - see [WP\_User\_Query](https://codex.wordpress.org/Class_Reference/WP_User_Query)).
>
>
>
`meta_value` is a very powerful way to go here. If you choose it, you have to define the `meta_key` which will then define what to order by.
>
> **meta\_key** - The **meta\_key** in the [wp\_usermeta table](https://codex.wordpress.org/Database_Description#Table:_wp_usermeta) for the **meta\_value** to be returned. See [get\_userdata()](https://codex.wordpress.org/Function_Reference/get_userdata#Values_in_users_.26_user_meta_table) for the possible meta keys.
>
>
>
`get_userdata()` can [return quite a lot of values,](https://codex.wordpress.org/Function_Reference/get_userdata#Notes) possibly enough to order by.
---
**Examples**
So, if you want to order by the users last name for example, use `get_users()` like this:
```
$your_users = get_users('orderby=meta_value&meta_key=last_name');
```
Order by first name
```
$your_users = get_users('orderby=meta_value&meta_key=first_name');
```
Order by registration date
```
$your_users = get_users('orderby=meta_value&meta_key=user_registered');
```
You can of course use `order` to reverse the sorting order
```
// Sorting users by registration date - ascending (standard behaviour)
$your_users = get_users('orderby=meta_value&meta_key=user_registered');
// Sorting users by registration date - descending (add order=DESC)
$your_users = get_users('orderby=meta_value&meta_key=user_registered&order=DESC');
```
---
**One step further**
If you want to order by user-defined values, which `get_userdata()` wonΒ΄t deliver, you can pass another parameter to `get_users()`.
```
$your_users = get_users('fields=all_with_meta');
```
This will result in an array which contains all meta data that is linked to a user. You can then use a custom sort function ([via usort()](https://secure.php.net/manual/function.usort.php)) to order by a specific parameter.
```
$your_users = get_users('fields=all_with_meta');
// very basic comparison...
function compare($a, $b) { return ($a->special > $b->special) ? -1 : 1; }
usort($your_users, 'compare');
```
|
206,292 |
<p>I have a site I'm building in wordpress that has ~80GB of high resolution images, and it's exceeding my managed host's storage space. My plan is to move all the images to S3, but I noticed that <code>wp_get_attachment_image()</code> automatically prefixes the src with <code>/wp-content/uploads</code> instead of respecting the path stored in the database.</p>
<p>Is there a way to hook into that method and modify it to not include the prefix?</p>
|
[
{
"answer_id": 206294,
"author": "Rubatharisan Thirumathyam",
"author_id": 64091,
"author_profile": "https://wordpress.stackexchange.com/users/64091",
"pm_score": 2,
"selected": true,
"text": "<p>It might be a solution to string replace /wp-content/uploads with '' (empty) like for an example:</p>\n\n<p>Lets say: wp_get_attachment_image() returns = '/wp-content/uploads/myimage.png';</p>\n\n<pre><code><?php\necho str_replace('/wp-content/uploads/', '', wp_get_attachment_image()); \n?>\n</code></pre>\n\n<p>This will result in echo: 'myimage.png'</p>\n\n<p>Try this:</p>\n\n<pre><code>function alter_image_src($attr) {\n $attr['src'] = str_replace('/wp-content/uploads/', '', $attr['src']);\n return $attr;\n}\nadd_filter( 'wp_get_attachment_image_attributes', 'alter_image_src');\n</code></pre>\n\n<p>In your functions page (of theme). </p>\n"
},
{
"answer_id": 206297,
"author": "AgmLauncher",
"author_id": 49143,
"author_profile": "https://wordpress.stackexchange.com/users/49143",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like I can intercept and str_replace in an intercept on <code>wp_get_attachment_image_attributes()</code>, which is used by the higher level <code>wp_get_attachment_image()</code> function. </p>\n"
}
] |
2015/10/22
|
[
"https://wordpress.stackexchange.com/questions/206292",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/49143/"
] |
I have a site I'm building in wordpress that has ~80GB of high resolution images, and it's exceeding my managed host's storage space. My plan is to move all the images to S3, but I noticed that `wp_get_attachment_image()` automatically prefixes the src with `/wp-content/uploads` instead of respecting the path stored in the database.
Is there a way to hook into that method and modify it to not include the prefix?
|
It might be a solution to string replace /wp-content/uploads with '' (empty) like for an example:
Lets say: wp\_get\_attachment\_image() returns = '/wp-content/uploads/myimage.png';
```
<?php
echo str_replace('/wp-content/uploads/', '', wp_get_attachment_image());
?>
```
This will result in echo: 'myimage.png'
Try this:
```
function alter_image_src($attr) {
$attr['src'] = str_replace('/wp-content/uploads/', '', $attr['src']);
return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'alter_image_src');
```
In your functions page (of theme).
|
206,320 |
<p>I'm developing a responsive WordPress theme and instead of using frameworks, I've created one my own.</p>
<p>I'm trying NOT to repeat myself (meaning, I don't want to write extra markup all the time), so I'm generating the HTML that comes before the <code>.grid-unit div</code> element with a <code>fluid_grid</code> PHP function that takes a function as a first parameter.</p>
<p>I'm pulling some custom post types using <code>WP_Query</code>:</p>
<pre><code>function slider_template() {
// Query Arguments
$args = array(
'post_type' => 'slides',
'posts_per_page' => 10
);
// The Query
$the_query = new WP_Query( $args );
// Check if the Query returns any posts
if ( $the_query->have_posts() ) {
// I'm passing an anonymous function here, that needs to be called later on
fluid_grid( function() {
?>
// Here goes the markup that should be printed out later
<?php
} ); // Close the anonymous function, and end the fluid_grid function.
} // End of the if statement
} // End of slider_template function
</code></pre>
<p>After visiting the page, I'm getting the following error:</p>
<p><code>Fatal error: Call to a member function have_posts() on null in ...</code></p>
<p>I've tried making the <code>$the_query</code> global, but ended up with the same result (<code>$the_query</code> is still null).</p>
<p>Is it possible to get <code>$the_query</code> variable working inside the anonymous function? If so, how?</p>
|
[
{
"answer_id": 206328,
"author": "Chris",
"author_id": 7435,
"author_profile": "https://wordpress.stackexchange.com/users/7435",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not familiar with <code>fluid_grid</code>, but this looks like a scope issue. You are creating an anonymous function inside your call:</p>\n\n<pre><code>fluid_grid(function() {\n\n});\n</code></pre>\n\n<p>This function does not have access to <code>$the_query</code>. You need to see if you can pass the query var to the function, or try globalizing it.</p>\n\n<pre><code>fluid_grid(function() {\n global $the_query;\n //do stuff \n});\n</code></pre>\n"
},
{
"answer_id": 206334,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>This is basic PHP. Just a note before I continue, never ever globalize variables. Wordpress has already done quite a crappy job regarding this. Globalization is evil, because anyone and anything, knowingly or unknowingly can change a global variable. This makes globals a nightmare to debug. So in short, <strong>NEVER EVER</strong> globalize.</p>\n\n<p>Whenever you need to pass something outside a anonymous function to the function, you should use the <code>use()</code> keyword. As example, you can try</p>\n\n<pre><code>function () use( $the_query )\n{\n var_dump( $the_query );\n}\n</code></pre>\n\n<h2>EDIT:</h2>\n\n<p>In your code, you can do the following</p>\n\n<pre><code>fluid_grid( function() use ( $the_query )\n{\n ?> \n // Here goes the markup that should be printed out later \n <?php\n} ); \n</code></pre>\n"
}
] |
2015/10/22
|
[
"https://wordpress.stackexchange.com/questions/206320",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82363/"
] |
I'm developing a responsive WordPress theme and instead of using frameworks, I've created one my own.
I'm trying NOT to repeat myself (meaning, I don't want to write extra markup all the time), so I'm generating the HTML that comes before the `.grid-unit div` element with a `fluid_grid` PHP function that takes a function as a first parameter.
I'm pulling some custom post types using `WP_Query`:
```
function slider_template() {
// Query Arguments
$args = array(
'post_type' => 'slides',
'posts_per_page' => 10
);
// The Query
$the_query = new WP_Query( $args );
// Check if the Query returns any posts
if ( $the_query->have_posts() ) {
// I'm passing an anonymous function here, that needs to be called later on
fluid_grid( function() {
?>
// Here goes the markup that should be printed out later
<?php
} ); // Close the anonymous function, and end the fluid_grid function.
} // End of the if statement
} // End of slider_template function
```
After visiting the page, I'm getting the following error:
`Fatal error: Call to a member function have_posts() on null in ...`
I've tried making the `$the_query` global, but ended up with the same result (`$the_query` is still null).
Is it possible to get `$the_query` variable working inside the anonymous function? If so, how?
|
This is basic PHP. Just a note before I continue, never ever globalize variables. Wordpress has already done quite a crappy job regarding this. Globalization is evil, because anyone and anything, knowingly or unknowingly can change a global variable. This makes globals a nightmare to debug. So in short, **NEVER EVER** globalize.
Whenever you need to pass something outside a anonymous function to the function, you should use the `use()` keyword. As example, you can try
```
function () use( $the_query )
{
var_dump( $the_query );
}
```
EDIT:
-----
In your code, you can do the following
```
fluid_grid( function() use ( $the_query )
{
?>
// Here goes the markup that should be printed out later
<?php
} );
```
|
206,330 |
<p>Is this possible in WordPress?</p>
<p>Like if I use a piece of code to display Post1 image+title and some more code to display six more posts in that category...</p>
<p>But then to do the next category I have to paste the whole code in again and change the category.</p>
<p>Can I just code "repeat, but change variable to ___ and variable to ____?</p>
<p>Thanks,
JH</p>
<pre><code>---
<div class="category-container">
<div class="category-container-category-title" style="background-color:#004377;">
Cat 1
</div>
<div class="category-container-category-post" >
<?php $posts = get_posts( "cat='50'&numberposts=1" ); ?>
<?php if( $posts ) : ?>
<?php foreach( $posts as $post ) : setup_postdata( $post ); ?>
<a href="<?php echo get_permalink($post->ID); ?>" >
<div class="thumbnail-box" style="background-color:#004377;">
<?php if ( has_post_thumbnail()) : the_post_thumbnail('thumb-thumb'); endif; ?>
<h3><?php echo $post->post_title; ?></h3>
</div>
</a>
<?php endforeach; ?>
<?php endif; ?>
</div>
</div>
<div class="category-container-category-posts">
<?php
$args=array(
'cat' => '50',
'offset' => 1,
'showposts'=>6,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
$offset = 3;
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
<div>
<h5 style="padding-bottom:25px;"><b>
<?php the_title(); ?></b>
</h5>
</div>
</a>
<?php
endwhile;
} //if ($my_query)
wp_reset_query(); // Restore global post data stomped by the_post().
?>
</div>
---
</code></pre>
|
[
{
"answer_id": 206328,
"author": "Chris",
"author_id": 7435,
"author_profile": "https://wordpress.stackexchange.com/users/7435",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not familiar with <code>fluid_grid</code>, but this looks like a scope issue. You are creating an anonymous function inside your call:</p>\n\n<pre><code>fluid_grid(function() {\n\n});\n</code></pre>\n\n<p>This function does not have access to <code>$the_query</code>. You need to see if you can pass the query var to the function, or try globalizing it.</p>\n\n<pre><code>fluid_grid(function() {\n global $the_query;\n //do stuff \n});\n</code></pre>\n"
},
{
"answer_id": 206334,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>This is basic PHP. Just a note before I continue, never ever globalize variables. Wordpress has already done quite a crappy job regarding this. Globalization is evil, because anyone and anything, knowingly or unknowingly can change a global variable. This makes globals a nightmare to debug. So in short, <strong>NEVER EVER</strong> globalize.</p>\n\n<p>Whenever you need to pass something outside a anonymous function to the function, you should use the <code>use()</code> keyword. As example, you can try</p>\n\n<pre><code>function () use( $the_query )\n{\n var_dump( $the_query );\n}\n</code></pre>\n\n<h2>EDIT:</h2>\n\n<p>In your code, you can do the following</p>\n\n<pre><code>fluid_grid( function() use ( $the_query )\n{\n ?> \n // Here goes the markup that should be printed out later \n <?php\n} ); \n</code></pre>\n"
}
] |
2015/10/23
|
[
"https://wordpress.stackexchange.com/questions/206330",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77987/"
] |
Is this possible in WordPress?
Like if I use a piece of code to display Post1 image+title and some more code to display six more posts in that category...
But then to do the next category I have to paste the whole code in again and change the category.
Can I just code "repeat, but change variable to \_\_\_ and variable to \_\_\_\_?
Thanks,
JH
```
---
<div class="category-container">
<div class="category-container-category-title" style="background-color:#004377;">
Cat 1
</div>
<div class="category-container-category-post" >
<?php $posts = get_posts( "cat='50'&numberposts=1" ); ?>
<?php if( $posts ) : ?>
<?php foreach( $posts as $post ) : setup_postdata( $post ); ?>
<a href="<?php echo get_permalink($post->ID); ?>" >
<div class="thumbnail-box" style="background-color:#004377;">
<?php if ( has_post_thumbnail()) : the_post_thumbnail('thumb-thumb'); endif; ?>
<h3><?php echo $post->post_title; ?></h3>
</div>
</a>
<?php endforeach; ?>
<?php endif; ?>
</div>
</div>
<div class="category-container-category-posts">
<?php
$args=array(
'cat' => '50',
'offset' => 1,
'showposts'=>6,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
$offset = 3;
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
<div>
<h5 style="padding-bottom:25px;"><b>
<?php the_title(); ?></b>
</h5>
</div>
</a>
<?php
endwhile;
} //if ($my_query)
wp_reset_query(); // Restore global post data stomped by the_post().
?>
</div>
---
```
|
This is basic PHP. Just a note before I continue, never ever globalize variables. Wordpress has already done quite a crappy job regarding this. Globalization is evil, because anyone and anything, knowingly or unknowingly can change a global variable. This makes globals a nightmare to debug. So in short, **NEVER EVER** globalize.
Whenever you need to pass something outside a anonymous function to the function, you should use the `use()` keyword. As example, you can try
```
function () use( $the_query )
{
var_dump( $the_query );
}
```
EDIT:
-----
In your code, you can do the following
```
fluid_grid( function() use ( $the_query )
{
?>
// Here goes the markup that should be printed out later
<?php
} );
```
|
206,353 |
<p>I want to disable the email notification if a user or an admin changes the password of a user.<br></p>
<p>After some Googling I came to find that I need to create a plugin and overwrite the <code>wp_password_change_notification</code> function found in <code>pluggable.php</code>.</p>
<p>This is the plugin and function:</p>
<pre><code><?php
/*
Plugin Name: Stop email change password
Description: Whatever
*/
if ( !function_exists( 'wp_password_change_notification' ) ) {
function wp_password_change_notification() {}
}
?>
</code></pre>
<p>I uploaded the file to my plugin folder and activated it in my admin panel!</p>
<p>This needs to be done with a plugin because the <code>pluggable.php</code> file is loaded before the <code>functions.php</code> file.</p>
<p>Anyway it doesn't seem to work for me.</p>
<p>The user still receives the email.</p>
<p>I disabled all plugins and run the plugin on a clean install so no interference</p>
<p>The <code>WP_DEBUG</code> doesn't show any errors as well!</p>
<p>Can anybody tell me what to change or how to fix it any other way (except core modifications :-))</p>
<p>M.</p>
|
[
{
"answer_id": 206354,
"author": "Sabbir Hasan",
"author_id": 76587,
"author_profile": "https://wordpress.stackexchange.com/users/76587",
"pm_score": 2,
"selected": false,
"text": "<p>Copy this following code and save as disable_email.php . Then place that file in \"wp-content/plugins/\" directory. And active from Admin Panel.</p>\n\n<pre><code><?php\n/*\nPlugin Name: Stop email change password\nDescription: Whatever\n*/\n\nif (!function_exists('wp_password_change_notification')) {\n function wp_password_change_notification($user) {\n return;\n }\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 206396,
"author": "user42826",
"author_id": 42826,
"author_profile": "https://wordpress.stackexchange.com/users/42826",
"pm_score": 5,
"selected": false,
"text": "<p>To disable user email notification, add this in a plugin or theme:</p>\n\n<pre><code>add_filter( 'send_password_change_email', '__return_false' );\n</code></pre>\n\n<p>FYI <a href=\"https://developer.wordpress.org/reference/functions/wp_password_change_notification/\" rel=\"noreferrer\"><code>wp_password_change_notification()</code></a> controls admin email notification when a user changes their password</p>\n"
},
{
"answer_id": 218577,
"author": "Meint-Willem Gaasbeek",
"author_id": 89285,
"author_profile": "https://wordpress.stackexchange.com/users/89285",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress sends the notification by default when the user is updated with <code>wp_update_user()</code>. </p>\n\n<p>Trying to overwrite this using filters, modifying <code>pluggable.php</code>, or overwriting with an empty function, doesn't work.</p>\n\n<p>Instead use <code>wp_set_password( $password, $user_id )</code> when you don't want the notification e-mail to be triggered for users/admins on a password reset.</p>\n"
},
{
"answer_id": 266006,
"author": "rjb",
"author_id": 8495,
"author_profile": "https://wordpress.stackexchange.com/users/8495",
"pm_score": 5,
"selected": false,
"text": "<p>To disable <em>Admin email notification</em> when a <strong>user resets their own password</strong>, create a Plugin (or <a href=\"https://www.sitepoint.com/wordpress-mu-plugins/\" rel=\"noreferrer\">Must Use Plugin</a>) using the following code snippet:</p>\n\n<pre><code>/**\n * Disable Admin Notification of User Password Change\n *\n * @see pluggable.php\n */\nif ( ! function_exists( 'wp_password_change_notification' ) ) {\n function wp_password_change_notification( $user ) {\n return;\n }\n}\n</code></pre>\n\n<p>This will stop the following email from being sent to the Administrator's Email in Settings > General:</p>\n\n<blockquote>\n <p><strong>From:</strong> WordPress <[email protected]><br>\n <strong>To:</strong> [email protected]<br>\n <strong>Subject:</strong> [WordPress] Password Changed </p>\n \n <p>Password changed for user: username</p>\n</blockquote>\n\n<p>Suppressing this email notification has to handled with a plugin because <code>pluggable.php</code> is loaded earlier than a theme's <code>functions.php</code> file.</p>\n\n<hr>\n\n<p>If you wish to instead disable <em>User email notification</em> that a <strong>user has successfully changed their own password</strong>, use the following filter placed in <code>functions.php</code>:</p>\n\n<pre><code>/**\n * Disable User Notification of Password Change Confirmation\n */\nadd_filter( 'send_password_change_email', '__return_false' );\n</code></pre>\n\n<p>This will suppress the following email from being sent:</p>\n\n<blockquote>\n <p><strong>From:</strong> WordPress <[email protected]><br>\n <strong>To:</strong> [email protected]<br>\n <strong>Subject:</strong> [WordPress] Password Changed </p>\n \n <p>Hi username,</p>\n \n <p>This notice confirms that your password was changed on WordPress.</p>\n \n <p>If you did not change your password, please contact the Site Administrator at [email protected]</p>\n \n <p>This email has been sent to [email protected]</p>\n \n <p>Regards,<br>\n All at WordPress<br>\n <a href=\"http://example.com/\" rel=\"noreferrer\">http://example.com/</a></p>\n</blockquote>\n"
},
{
"answer_id": 270047,
"author": "wynnset",
"author_id": 121742,
"author_profile": "https://wordpress.stackexchange.com/users/121742",
"pm_score": 1,
"selected": false,
"text": "<p>Other answers are wrong because those disable sending email when email is changed, not when password is changed. </p>\n\n<p>Adding the code below into your functions.php file under your active theme (or alternatively in a plugin) should work. Worked for me for version 4.6.1</p>\n\n<pre><code>/**\n * Disable sending of the password change email\n */\nadd_filter( 'send_password_change_email', '__return_false' );\n</code></pre>\n\n<p>See <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/send_password_change_email\" rel=\"nofollow noreferrer\">official documentation</a></p>\n"
},
{
"answer_id": 288792,
"author": "Andrew Schultz",
"author_id": 101154,
"author_profile": "https://wordpress.stackexchange.com/users/101154",
"pm_score": 1,
"selected": false,
"text": "<p>Use the function <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_password\" rel=\"nofollow noreferrer\">wp_set_password()</a> instead of wp_update_user() to update the password as this won't trigger an email notification.</p>\n"
},
{
"answer_id": 364750,
"author": "Mikepote",
"author_id": 37879,
"author_profile": "https://wordpress.stackexchange.com/users/37879",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using Woocommerce:</p>\n\n<p>Since WC 3.8.0 (November 2019), there is now a dedicated filter hook for this:</p>\n\n<pre><code>add_filter('woocommerce_disable_password_change_notification', '__return_true');\n</code></pre>\n\n<p>Should suppress password change notifications.</p>\n"
},
{
"answer_id": 378326,
"author": "megseoh",
"author_id": 73347,
"author_profile": "https://wordpress.stackexchange.com/users/73347",
"pm_score": 0,
"selected": false,
"text": "<p>Should this answer <a href=\"https://wordpress.stackexchange.com/a/266006/73347\">https://wordpress.stackexchange.com/a/266006/73347</a> above still work to disable password reset emails to admins?</p>\n<pre><code>/**\n * Disable Admin Notification of User Password Change\n *\n * @see pluggable.php\n */\nif ( ! function_exists( 'wp_password_change_notification' ) ) {\n function wp_password_change_notification( $user ) {\n return;\n }\n}\n</code></pre>\n<p>I'm still receiving them :(\nThanks.</p>\n"
},
{
"answer_id": 402494,
"author": "Mike van den Hoek",
"author_id": 140554,
"author_profile": "https://wordpress.stackexchange.com/users/140554",
"pm_score": 2,
"selected": false,
"text": "<p>This works for me, just clear the email address.</p>\n<pre><code>// Disable password change notification email.\nadd_filter('wp_password_change_notification_email', function ($wp_password_change_notification_email) {\n $wp_password_change_notification_email['to'] = '';\n return $wp_password_change_notification_email;\n});\n</code></pre>\n"
},
{
"answer_id": 414296,
"author": "Rohjay",
"author_id": 204861,
"author_profile": "https://wordpress.stackexchange.com/users/204861",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>wp_password_change_notification</code> function is responsible for this functionality inside WordPress that emails admins these user password change updates (as other posts have mentioned).</p>\n<p>What I haven't seen here is that inside <code>./wp-includes/default-filters.php</code> ~line 499 (at the time of this writing) you'll see this function being added to the <code>after_password_reset</code> action.</p>\n<p>A quick fix is then to simply remove it from the action list:</p>\n<pre class=\"lang-php prettyprint-override\"><code>remove_action( 'after_password_reset', 'wp_password_change_notification' );\n</code></pre>\n<p>You absolutely can rewrite/overwrite <code>wp_password_change_notification</code>, as it is one of the <code>pluggable.php</code> functions, but if you're looking to remove this functionality rather than update it, this might be a better option.</p>\n"
}
] |
2015/10/23
|
[
"https://wordpress.stackexchange.com/questions/206353",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52240/"
] |
I want to disable the email notification if a user or an admin changes the password of a user.
After some Googling I came to find that I need to create a plugin and overwrite the `wp_password_change_notification` function found in `pluggable.php`.
This is the plugin and function:
```
<?php
/*
Plugin Name: Stop email change password
Description: Whatever
*/
if ( !function_exists( 'wp_password_change_notification' ) ) {
function wp_password_change_notification() {}
}
?>
```
I uploaded the file to my plugin folder and activated it in my admin panel!
This needs to be done with a plugin because the `pluggable.php` file is loaded before the `functions.php` file.
Anyway it doesn't seem to work for me.
The user still receives the email.
I disabled all plugins and run the plugin on a clean install so no interference
The `WP_DEBUG` doesn't show any errors as well!
Can anybody tell me what to change or how to fix it any other way (except core modifications :-))
M.
|
To disable user email notification, add this in a plugin or theme:
```
add_filter( 'send_password_change_email', '__return_false' );
```
FYI [`wp_password_change_notification()`](https://developer.wordpress.org/reference/functions/wp_password_change_notification/) controls admin email notification when a user changes their password
|
206,394 |
<p>I'm correctly developing my own theme and so far I got: index, header, footer, functions and style files. The list will go on as I'm progressing with my theme. But I'm considering to use more than one theme at this site with total different files and I'm thinking of using simply different names for files instead the original ones, so instead of header.php it would be blabla.php and so on. With different data inside them, of course.
So... therefor I have very important questions:</p>
<p>Would this method may make any conflict in WP core or something like this? </p>
|
[
{
"answer_id": 206397,
"author": "Dan Gayle",
"author_id": 10,
"author_profile": "https://wordpress.stackexchange.com/users/10",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the <code>get_template_part</code> to load different files into your template, using whatever combination of name/slug you want. Works friendly with child themes also, which might be worth investigating if you want to have multiple different themes. </p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_template_part\" rel=\"nofollow\">The documentation says</a>:</p>\n\n<blockquote>\n <p><strong>Function Reference/get template part</strong></p>\n \n <p>Load a template part (other than header, sidebar, footer) into a\n template. Makes it easy for a theme to reuse sections of code and an\n easy way for child themes to replace sections of their parent theme.</p>\n</blockquote>\n\n<p>Pretty easy to use too:</p>\n\n<pre><code># if you want to include blabla.php into your template\n<?php get_template_part( 'blabla' ); ?> \n</code></pre>\n"
},
{
"answer_id": 206398,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>You probably are over complicating things for yourself. You can use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include\" rel=\"nofollow\">template_include</a> filter for that</p>\n\n<pre><code>add_filter( 'template_include', 'wpse_206394_template', 99 );\n\nfunction wpse_206394_template( $template ) {\n\n if ( template should be blabla ) {\n $new_template = locate_template( array( str_replace('.php','-blabla.php',$template) ) );\n if ( '' != $new_template ) {\n return $new_template ;\n }\n }\n\n return $template;\n}\n</code></pre>\n\n<p>but most likely you can get the same effect with proper use of the template hierarchy.</p>\n"
}
] |
2015/10/23
|
[
"https://wordpress.stackexchange.com/questions/206394",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82409/"
] |
I'm correctly developing my own theme and so far I got: index, header, footer, functions and style files. The list will go on as I'm progressing with my theme. But I'm considering to use more than one theme at this site with total different files and I'm thinking of using simply different names for files instead the original ones, so instead of header.php it would be blabla.php and so on. With different data inside them, of course.
So... therefor I have very important questions:
Would this method may make any conflict in WP core or something like this?
|
You probably are over complicating things for yourself. You can use the [template\_include](https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include) filter for that
```
add_filter( 'template_include', 'wpse_206394_template', 99 );
function wpse_206394_template( $template ) {
if ( template should be blabla ) {
$new_template = locate_template( array( str_replace('.php','-blabla.php',$template) ) );
if ( '' != $new_template ) {
return $new_template ;
}
}
return $template;
}
```
but most likely you can get the same effect with proper use of the template hierarchy.
|
206,395 |
<p>I moved over a development site to the client's hosting server using the WP Clone plugin. It seemed to work just fine, until I noticed a bunch of odd question marks where things like em-dashes and apostrophes should be.</p>
<p>It appears to be a unicode issue, but the only difference I can tell between the two servers is that the client-side is using utf8mb4_unicode_c and my development server is using utf8_unicode_ci.</p>
<p>If I copy and paste a page from the development side to the client side, it displays fine β but I'd rather not have to do that for the entire site (50-plus pages plus a few dozen posts).</p>
<p>I tried exporting the database table from the development site and importing it on the client side, but that led to a bunch of warning messages and everything on the client home page linked back to the development site. </p>
<p>Any ideas on how I can fix this, short of a manual cut-and-paste job?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 206397,
"author": "Dan Gayle",
"author_id": 10,
"author_profile": "https://wordpress.stackexchange.com/users/10",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the <code>get_template_part</code> to load different files into your template, using whatever combination of name/slug you want. Works friendly with child themes also, which might be worth investigating if you want to have multiple different themes. </p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_template_part\" rel=\"nofollow\">The documentation says</a>:</p>\n\n<blockquote>\n <p><strong>Function Reference/get template part</strong></p>\n \n <p>Load a template part (other than header, sidebar, footer) into a\n template. Makes it easy for a theme to reuse sections of code and an\n easy way for child themes to replace sections of their parent theme.</p>\n</blockquote>\n\n<p>Pretty easy to use too:</p>\n\n<pre><code># if you want to include blabla.php into your template\n<?php get_template_part( 'blabla' ); ?> \n</code></pre>\n"
},
{
"answer_id": 206398,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>You probably are over complicating things for yourself. You can use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include\" rel=\"nofollow\">template_include</a> filter for that</p>\n\n<pre><code>add_filter( 'template_include', 'wpse_206394_template', 99 );\n\nfunction wpse_206394_template( $template ) {\n\n if ( template should be blabla ) {\n $new_template = locate_template( array( str_replace('.php','-blabla.php',$template) ) );\n if ( '' != $new_template ) {\n return $new_template ;\n }\n }\n\n return $template;\n}\n</code></pre>\n\n<p>but most likely you can get the same effect with proper use of the template hierarchy.</p>\n"
}
] |
2015/10/23
|
[
"https://wordpress.stackexchange.com/questions/206395",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82411/"
] |
I moved over a development site to the client's hosting server using the WP Clone plugin. It seemed to work just fine, until I noticed a bunch of odd question marks where things like em-dashes and apostrophes should be.
It appears to be a unicode issue, but the only difference I can tell between the two servers is that the client-side is using utf8mb4\_unicode\_c and my development server is using utf8\_unicode\_ci.
If I copy and paste a page from the development side to the client side, it displays fine β but I'd rather not have to do that for the entire site (50-plus pages plus a few dozen posts).
I tried exporting the database table from the development site and importing it on the client side, but that led to a bunch of warning messages and everything on the client home page linked back to the development site.
Any ideas on how I can fix this, short of a manual cut-and-paste job?
Thanks!
|
You probably are over complicating things for yourself. You can use the [template\_include](https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include) filter for that
```
add_filter( 'template_include', 'wpse_206394_template', 99 );
function wpse_206394_template( $template ) {
if ( template should be blabla ) {
$new_template = locate_template( array( str_replace('.php','-blabla.php',$template) ) );
if ( '' != $new_template ) {
return $new_template ;
}
}
return $template;
}
```
but most likely you can get the same effect with proper use of the template hierarchy.
|
206,406 |
<p>My args array:</p>
<pre><code>$args = array (
'cat' => '1,3,7',
'posts_per_page' => '30'
);
</code></pre>
<p>How to define <code>posts_per_page</code>:</p>
<ul>
<li><p>category 1 : 7 posts,</p></li>
<li><p>category 3 : 10 posts,</p></li>
<li><p>category 7 : 13 posts,</p></li>
</ul>
|
[
{
"answer_id": 206397,
"author": "Dan Gayle",
"author_id": 10,
"author_profile": "https://wordpress.stackexchange.com/users/10",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the <code>get_template_part</code> to load different files into your template, using whatever combination of name/slug you want. Works friendly with child themes also, which might be worth investigating if you want to have multiple different themes. </p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_template_part\" rel=\"nofollow\">The documentation says</a>:</p>\n\n<blockquote>\n <p><strong>Function Reference/get template part</strong></p>\n \n <p>Load a template part (other than header, sidebar, footer) into a\n template. Makes it easy for a theme to reuse sections of code and an\n easy way for child themes to replace sections of their parent theme.</p>\n</blockquote>\n\n<p>Pretty easy to use too:</p>\n\n<pre><code># if you want to include blabla.php into your template\n<?php get_template_part( 'blabla' ); ?> \n</code></pre>\n"
},
{
"answer_id": 206398,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>You probably are over complicating things for yourself. You can use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include\" rel=\"nofollow\">template_include</a> filter for that</p>\n\n<pre><code>add_filter( 'template_include', 'wpse_206394_template', 99 );\n\nfunction wpse_206394_template( $template ) {\n\n if ( template should be blabla ) {\n $new_template = locate_template( array( str_replace('.php','-blabla.php',$template) ) );\n if ( '' != $new_template ) {\n return $new_template ;\n }\n }\n\n return $template;\n}\n</code></pre>\n\n<p>but most likely you can get the same effect with proper use of the template hierarchy.</p>\n"
}
] |
2015/10/24
|
[
"https://wordpress.stackexchange.com/questions/206406",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82085/"
] |
My args array:
```
$args = array (
'cat' => '1,3,7',
'posts_per_page' => '30'
);
```
How to define `posts_per_page`:
* category 1 : 7 posts,
* category 3 : 10 posts,
* category 7 : 13 posts,
|
You probably are over complicating things for yourself. You can use the [template\_include](https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include) filter for that
```
add_filter( 'template_include', 'wpse_206394_template', 99 );
function wpse_206394_template( $template ) {
if ( template should be blabla ) {
$new_template = locate_template( array( str_replace('.php','-blabla.php',$template) ) );
if ( '' != $new_template ) {
return $new_template ;
}
}
return $template;
}
```
but most likely you can get the same effect with proper use of the template hierarchy.
|
206,424 |
<p>Im trying to convert the post title to an image.
i created a php file in the theme folder image.php
with the code
UPDATE: working code</p>
<pre><code>require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
$postid = $_GET["postid"];
$string = get_the_title($postid);
$im = imagecreate(100, 30);
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
imagestring($im, 5, 0, 0, $string, $textcolor);
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
</code></pre>
<p>and i call the file with</p>
<pre><code><img src="url/wp-content/themes/v2/image.php?postid=<?php echo $post->ID ?>" />
</code></pre>
<p>ok now to my problem: the image gets created but without the post title.
Do i need to include anything else to get the_title to execute?</p>
|
[
{
"answer_id": 206431,
"author": "Arif",
"author_id": 81715,
"author_profile": "https://wordpress.stackexchange.com/users/81715",
"pm_score": 0,
"selected": false,
"text": "<p>I think in image.php, post Id is blank, and so not getting anything. moreover - is this the only code in image.php? You need to make sure WordPress system gets loaded before calling get_the_title & pass postid from caller to image.php like - image.php?pid=223</p>\n\n<p>Load Wordpress at the top of your image.php file:</p>\n\n<pre><code>require('./wp-load.php');\n</code></pre>\n\n<p>Grab the postid from URL param:</p>\n\n<pre><code>$postID = $_GET['pid'];\n</code></pre>\n\n<p>Then rest of your code goes as is.</p>\n\n<p>When calling this script in image tags src, make sure to pass the correct pid </p>\n\n<pre><code>src=\"image.php?pid=xxx\"\n</code></pre>\n"
},
{
"answer_id": 206433,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<h2>In General</h2>\n\n<p>The problem here is that you're calling a WordPress function within a PHP file where WordPress isn't loaded.</p>\n\n<p>Including WordPress in your <code>image.php</code> file might work if you include the post ID </p>\n\n<pre><code><img src=\"/wp-content/themes/v2/image.php?post_id=123\" />\n</code></pre>\n\n<p>But imagine if you have 100 images on a single page, then you would be running 101 instances of WordPress! </p>\n\n<p>You might try to hook into WordPress and run only minimized version of WordPress, but then we are still running PHP for each of those images.</p>\n\n<p>Another approach would be to avoid any WordPress calls in your <code>image.php</code> file and grab only the title text:</p>\n\n<pre><code><img src=\"/wp-content/themes/v2/image.php?title=Hello+World!\" />\n</code></pre>\n\n<p>But here the danger is that anyone could create an image with any kind of text. That's not good. You could add restrictions, like checking the referrer, but that might not be \"watertight\".</p>\n\n<p>Better approach might be to create the image files when the post title is modified. Then we can simply call the image file with:</p>\n\n<pre><code><img src=\"/wp-content/uploads/titles/image-123.png\" />\n</code></pre>\n\n<p>but with things like browser caching, we might need a cache buster:</p>\n\n<pre><code><img src=\"/wp-content/uploads/titles/image-123.png?last-modified=1445683693 \" />\n</code></pre>\n\n<p>We might also use the post title in the image file name:</p>\n\n<pre><code><img src=\"/wp-content/uploads/titles/image-hello-world.png\" />\n</code></pre>\n\n<p>The only thing here is we would need to generate those images for old posts. </p>\n\n<p>Let's take a closer look at the last mentioned approach.</p>\n\n<h2>Implementation</h2>\n\n<p>Let's assume we have the GD image package installed on our server. Then we could extend the <code>WP_Image_Editor_GD</code> class to our needs:</p>\n\n<pre><code>class WPSE_Image_Editor_GD extends WP_Image_Editor_GD\n{\n private $wpse_bgclr;\n private $wpse_txtclr;\n private $wpse_txt;\n\n public function wpse_new( $width = 0, $height = 0 ) \n {\n $this->image = imagecreate( $width, $height );\n return $this;\n }\n\n protected function wpse_color( $red = 0, $green = 0, $blue = 0 )\n {\n return imagecolorallocate( $this->image, (int) $red, (int) $green, (int) $blue );\n }\n\n public function wpse_textcolor( $red = 0, $green = 0, $blue = 0 )\n {\n $this->wpse_txtclr = $this->wpse_color( (int) $red, (int) $green, (int) $blue );\n return $this;\n }\n\n public function wpse_bgcolor( $red = 0, $green = 0, $blue = 0 )\n {\n $this->wpse_bgclr = $this->wpse_color( (int) $red, (int) $green, (int) $blue );\n return $this;\n }\n\n public function wpse_text( $text ) \n { \n $this->wpse_txt = imagestring( $this->image, 5, 0, 0, $text, $this->wpse_txtclr );\n return $this;\n }\n\n}\n</code></pre>\n\n<p>Here we prefix our methods with <code>wpse_</code> to avoid possible name collisions in the future.</p>\n\n<p>It's also handy to return <code>$this</code> for <em>chaining</em>.</p>\n\n<p>We can get the current upload path with:</p>\n\n<pre><code>$upload_dir = wp_upload_dir();\n</code></pre>\n\n<p>and to set the upload path for the generated title <em>.png</em> files, we could use:</p>\n\n<pre><code>$file = sprintf( '%s/wpse_titles/image-%s.png', \n $upload_dir['basedir'], \n strtolower( sanitize_file_name( $post->post_title ) ) \n); \n</code></pre>\n\n<p>This would save the <em>Hello World</em> title to the file:</p>\n\n<pre><code>/wp-content/uploads/wpse_titles/image-hello-world.png\n</code></pre>\n\n<p>We could use the <code>save_post_{$post_type}</code> hook to target a specific post type updates.</p>\n\n<p>But don't want to generate it on each update, so let's check if it's a file that already exists with:</p>\n\n<pre><code>if( is_file( $file ) )\n return;\n</code></pre>\n\n<p>Now we can use our custom class and create an instance:</p>\n\n<pre><code>$o = new WPSE_Image_Editor_GD;\n</code></pre>\n\n<p>and create an empty image object, color it, add the post title string to it and then save it:</p>\n\n<pre><code> $result = $o\n ->wpse_new( 300, 60 ) // Width x height = 300 x 60\n ->wpse_bgcolor( 0, 0, 255 ) // Background color as Blue\n ->wpse_textcolor( 255, 255, 0 ) // Text color as Yellow\n ->wpse_text( $post->post_title ) // Hello World\n ->save( $file, 'image/png' ); // Save it to image-helloworld.png\n</code></pre>\n\n<h2>Output Example</h2>\n\n<p>Here's an example how the <em>image-helloworld.png</em> image would look like:</p>\n\n<p><a href=\"https://i.stack.imgur.com/g337M.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/g337M.png\" alt=\"hello world\"></a></p>\n\n<h2>Demo plugin</h2>\n\n<p>Here we add it all together in a demo plugin:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: WPSE Title Images\n * Description: On post update, create a png file of the post title (/uploads/wpse-titles/)\n * Plugin Author: Birgir Erlendsson (birgire)\n * Plurin URI: http://wordpress.stackexchange.com/a/206433/26350\n * Version: 0.0.2\n */\nadd_action( 'save_post_post', function( $post_id, $post )\n{\n // Ignore auto save or revisions\n if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) )\n return;\n\n if( class_exists( 'WPSE_Image_Editor_GD' ) )\n return;\n\n // Get the current upload path \n $upload_dir = wp_upload_dir();\n\n // Generated file path\n $file = sprintf( \n '%s/wpse_titles/image-%s.png', \n $upload_dir['basedir'], \n sanitize_key( $post->post_title ) \n ); \n\n // Only create it once\n if( is_file( $file ) )\n return;\n\n // Load the WP_Image_Editor and WP_Image_Editor_GD classes \n require_once ABSPATH . WPINC . '/class-wp-image-editor.php';\n require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';\n\n // Our custom extension\n class WPSE_Image_Editor_GD extends WP_Image_Editor_GD\n {\n private $wpse_bgclr;\n private $wpse_txtclr;\n private $wpse_txt;\n\n public function wpse_new( $width = 0, $height = 0 ) \n {\n $this->image = imagecreate( $width, $height ); \n return $this;\n }\n\n protected function wpse_color( $red = 0, $green = 0, $blue = 0 )\n {\n return imagecolorallocate( $this->image, (int) $red, (int) $green, (int) $blue );\n }\n\n public function wpse_textcolor( $red = 0, $green = 0, $blue = 0 )\n {\n $this->wpse_txtclr = $this->wpse_color( (int) $red, (int) $green, (int) $blue ); \n return $this;\n }\n\n public function wpse_bgcolor( $red = 0, $green = 0, $blue = 0 )\n {\n $this->wpse_bgclr = $this->wpse_color( (int) $red, (int) $green, (int) $blue ); \n return $this;\n }\n\n public function wpse_text( $text ) \n { \n $this->wpse_txt = imagestring( $this->image, 5, 0, 0, $text, $this->wpse_txtclr );\n return $this;\n }\n\n } // end class\n\n // Generate and save the title as a .png file \n $o = new WPSE_Image_Editor_GD;\n\n $result = $o\n ->wpse_new( 300, 60 ) // Width x height = 300 x 60\n ->wpse_bgcolor( 0, 0, 255 ) // Background color as Blue\n ->wpse_textcolor( 255, 255, 0 ) // Text color as Yellow\n ->wpse_text( $post->post_title ) // Hello World\n ->save( $file, 'image/png' ); // Save it to image-helloworld.png\n\n}, 10, 3 );\n</code></pre>\n\n<p>We might then create our own template tag, to display the image for each post:</p>\n\n<pre><code>if( function_exists( 'wpse_title_image' ) )\n wpse_title_image( $default_url = '' );\n</code></pre>\n\n<p>Here's an example, but in a proper plugin structure, we should be able to remove the duplicated code presented here:</p>\n\n<pre><code>/**\n * Get the current post's title image \n *\n * @param string $default_url Default image url\n * @return string $html Html for the title image\n */\nfunction get_wpse_title_image( $default_url = '' )\n{\n $post = get_post();\n $upload_dir = wp_upload_dir();\n $dirname = 'wpse_titles';\n\n $file = sprintf( \n 'image-%s.png',\n strtolower( sanitize_file_name( $post->post_title ) ) \n );\n\n $file_path = sprintf( \n '%s/%s/%s',\n $upload_dir['basedir'], \n $dirname,\n $file\n ); \n\n $file_url = sprintf( \n '%s/%s/%s',\n $upload_dir['baseurl'], \n $dirname,\n $file\n ); \n\n if( is_file( $file_path ) && is_readable( $file_path ) )\n $url = $file_url;\n else\n $url = $default_url;\n\n return sprintf( \n '<img src=\"%s\" alt=\"%s\">', \n esc_url( $url ),\n esc_attr( $post->post_title )\n );\n}\n</code></pre>\n\n<p>Then you can define the following wrapper:</p>\n\n<pre><code>/**\n * Display the current post's title image \n *\n * @uses get_wpse_title_image()\n *\n * @param string $default_url Default image url\n * @return void\n */\nfunction wpse_title_image( $default_url = '' )\n{\n echo get_wpse_title_image( $default_url );\n}\n</code></pre>\n\n<h2>Notes</h2>\n\n<p>This demo could be extended further, like:</p>\n\n<ul>\n<li>take this into a proper plugin structure</li>\n<li>adjusting the handling of the <em>width</em> and <em>height</em> of each title image. </li>\n<li>auto generate images for all posts</li>\n<li>do this for other post types</li>\n<li>... etc ...</li>\n</ul>\n"
}
] |
2015/10/24
|
[
"https://wordpress.stackexchange.com/questions/206424",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/56404/"
] |
Im trying to convert the post title to an image.
i created a php file in the theme folder image.php
with the code
UPDATE: working code
```
require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
$postid = $_GET["postid"];
$string = get_the_title($postid);
$im = imagecreate(100, 30);
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
imagestring($im, 5, 0, 0, $string, $textcolor);
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
```
and i call the file with
```
<img src="url/wp-content/themes/v2/image.php?postid=<?php echo $post->ID ?>" />
```
ok now to my problem: the image gets created but without the post title.
Do i need to include anything else to get the\_title to execute?
|
In General
----------
The problem here is that you're calling a WordPress function within a PHP file where WordPress isn't loaded.
Including WordPress in your `image.php` file might work if you include the post ID
```
<img src="/wp-content/themes/v2/image.php?post_id=123" />
```
But imagine if you have 100 images on a single page, then you would be running 101 instances of WordPress!
You might try to hook into WordPress and run only minimized version of WordPress, but then we are still running PHP for each of those images.
Another approach would be to avoid any WordPress calls in your `image.php` file and grab only the title text:
```
<img src="/wp-content/themes/v2/image.php?title=Hello+World!" />
```
But here the danger is that anyone could create an image with any kind of text. That's not good. You could add restrictions, like checking the referrer, but that might not be "watertight".
Better approach might be to create the image files when the post title is modified. Then we can simply call the image file with:
```
<img src="/wp-content/uploads/titles/image-123.png" />
```
but with things like browser caching, we might need a cache buster:
```
<img src="/wp-content/uploads/titles/image-123.png?last-modified=1445683693 " />
```
We might also use the post title in the image file name:
```
<img src="/wp-content/uploads/titles/image-hello-world.png" />
```
The only thing here is we would need to generate those images for old posts.
Let's take a closer look at the last mentioned approach.
Implementation
--------------
Let's assume we have the GD image package installed on our server. Then we could extend the `WP_Image_Editor_GD` class to our needs:
```
class WPSE_Image_Editor_GD extends WP_Image_Editor_GD
{
private $wpse_bgclr;
private $wpse_txtclr;
private $wpse_txt;
public function wpse_new( $width = 0, $height = 0 )
{
$this->image = imagecreate( $width, $height );
return $this;
}
protected function wpse_color( $red = 0, $green = 0, $blue = 0 )
{
return imagecolorallocate( $this->image, (int) $red, (int) $green, (int) $blue );
}
public function wpse_textcolor( $red = 0, $green = 0, $blue = 0 )
{
$this->wpse_txtclr = $this->wpse_color( (int) $red, (int) $green, (int) $blue );
return $this;
}
public function wpse_bgcolor( $red = 0, $green = 0, $blue = 0 )
{
$this->wpse_bgclr = $this->wpse_color( (int) $red, (int) $green, (int) $blue );
return $this;
}
public function wpse_text( $text )
{
$this->wpse_txt = imagestring( $this->image, 5, 0, 0, $text, $this->wpse_txtclr );
return $this;
}
}
```
Here we prefix our methods with `wpse_` to avoid possible name collisions in the future.
It's also handy to return `$this` for *chaining*.
We can get the current upload path with:
```
$upload_dir = wp_upload_dir();
```
and to set the upload path for the generated title *.png* files, we could use:
```
$file = sprintf( '%s/wpse_titles/image-%s.png',
$upload_dir['basedir'],
strtolower( sanitize_file_name( $post->post_title ) )
);
```
This would save the *Hello World* title to the file:
```
/wp-content/uploads/wpse_titles/image-hello-world.png
```
We could use the `save_post_{$post_type}` hook to target a specific post type updates.
But don't want to generate it on each update, so let's check if it's a file that already exists with:
```
if( is_file( $file ) )
return;
```
Now we can use our custom class and create an instance:
```
$o = new WPSE_Image_Editor_GD;
```
and create an empty image object, color it, add the post title string to it and then save it:
```
$result = $o
->wpse_new( 300, 60 ) // Width x height = 300 x 60
->wpse_bgcolor( 0, 0, 255 ) // Background color as Blue
->wpse_textcolor( 255, 255, 0 ) // Text color as Yellow
->wpse_text( $post->post_title ) // Hello World
->save( $file, 'image/png' ); // Save it to image-helloworld.png
```
Output Example
--------------
Here's an example how the *image-helloworld.png* image would look like:
[](https://i.stack.imgur.com/g337M.png)
Demo plugin
-----------
Here we add it all together in a demo plugin:
```
<?php
/**
* Plugin Name: WPSE Title Images
* Description: On post update, create a png file of the post title (/uploads/wpse-titles/)
* Plugin Author: Birgir Erlendsson (birgire)
* Plurin URI: http://wordpress.stackexchange.com/a/206433/26350
* Version: 0.0.2
*/
add_action( 'save_post_post', function( $post_id, $post )
{
// Ignore auto save or revisions
if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) )
return;
if( class_exists( 'WPSE_Image_Editor_GD' ) )
return;
// Get the current upload path
$upload_dir = wp_upload_dir();
// Generated file path
$file = sprintf(
'%s/wpse_titles/image-%s.png',
$upload_dir['basedir'],
sanitize_key( $post->post_title )
);
// Only create it once
if( is_file( $file ) )
return;
// Load the WP_Image_Editor and WP_Image_Editor_GD classes
require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
// Our custom extension
class WPSE_Image_Editor_GD extends WP_Image_Editor_GD
{
private $wpse_bgclr;
private $wpse_txtclr;
private $wpse_txt;
public function wpse_new( $width = 0, $height = 0 )
{
$this->image = imagecreate( $width, $height );
return $this;
}
protected function wpse_color( $red = 0, $green = 0, $blue = 0 )
{
return imagecolorallocate( $this->image, (int) $red, (int) $green, (int) $blue );
}
public function wpse_textcolor( $red = 0, $green = 0, $blue = 0 )
{
$this->wpse_txtclr = $this->wpse_color( (int) $red, (int) $green, (int) $blue );
return $this;
}
public function wpse_bgcolor( $red = 0, $green = 0, $blue = 0 )
{
$this->wpse_bgclr = $this->wpse_color( (int) $red, (int) $green, (int) $blue );
return $this;
}
public function wpse_text( $text )
{
$this->wpse_txt = imagestring( $this->image, 5, 0, 0, $text, $this->wpse_txtclr );
return $this;
}
} // end class
// Generate and save the title as a .png file
$o = new WPSE_Image_Editor_GD;
$result = $o
->wpse_new( 300, 60 ) // Width x height = 300 x 60
->wpse_bgcolor( 0, 0, 255 ) // Background color as Blue
->wpse_textcolor( 255, 255, 0 ) // Text color as Yellow
->wpse_text( $post->post_title ) // Hello World
->save( $file, 'image/png' ); // Save it to image-helloworld.png
}, 10, 3 );
```
We might then create our own template tag, to display the image for each post:
```
if( function_exists( 'wpse_title_image' ) )
wpse_title_image( $default_url = '' );
```
Here's an example, but in a proper plugin structure, we should be able to remove the duplicated code presented here:
```
/**
* Get the current post's title image
*
* @param string $default_url Default image url
* @return string $html Html for the title image
*/
function get_wpse_title_image( $default_url = '' )
{
$post = get_post();
$upload_dir = wp_upload_dir();
$dirname = 'wpse_titles';
$file = sprintf(
'image-%s.png',
strtolower( sanitize_file_name( $post->post_title ) )
);
$file_path = sprintf(
'%s/%s/%s',
$upload_dir['basedir'],
$dirname,
$file
);
$file_url = sprintf(
'%s/%s/%s',
$upload_dir['baseurl'],
$dirname,
$file
);
if( is_file( $file_path ) && is_readable( $file_path ) )
$url = $file_url;
else
$url = $default_url;
return sprintf(
'<img src="%s" alt="%s">',
esc_url( $url ),
esc_attr( $post->post_title )
);
}
```
Then you can define the following wrapper:
```
/**
* Display the current post's title image
*
* @uses get_wpse_title_image()
*
* @param string $default_url Default image url
* @return void
*/
function wpse_title_image( $default_url = '' )
{
echo get_wpse_title_image( $default_url );
}
```
Notes
-----
This demo could be extended further, like:
* take this into a proper plugin structure
* adjusting the handling of the *width* and *height* of each title image.
* auto generate images for all posts
* do this for other post types
* ... etc ...
|
206,435 |
<p>I am changing hosting + domain name for my WordPress site. For example now if its hosted on 201.0.0.1/mysite and now I want to upload it to mysite.com. This is what I did</p>
<p>exported database from my cpanel
got all files from server using filezilla (public_html folder that has Wordpress root folder as well)
set permalinks option to default and exported all content from existing site.
now planning to create a new database, setup wp-config.php and replace all files in public_html files.
My question is after doing all this will I face any issues regarding page / posts or any other links means it may not happen that I may get some broken links after doing all this. Is there any extra step required with all this mentioned above or is it okay?</p>
|
[
{
"answer_id": 206431,
"author": "Arif",
"author_id": 81715,
"author_profile": "https://wordpress.stackexchange.com/users/81715",
"pm_score": 0,
"selected": false,
"text": "<p>I think in image.php, post Id is blank, and so not getting anything. moreover - is this the only code in image.php? You need to make sure WordPress system gets loaded before calling get_the_title & pass postid from caller to image.php like - image.php?pid=223</p>\n\n<p>Load Wordpress at the top of your image.php file:</p>\n\n<pre><code>require('./wp-load.php');\n</code></pre>\n\n<p>Grab the postid from URL param:</p>\n\n<pre><code>$postID = $_GET['pid'];\n</code></pre>\n\n<p>Then rest of your code goes as is.</p>\n\n<p>When calling this script in image tags src, make sure to pass the correct pid </p>\n\n<pre><code>src=\"image.php?pid=xxx\"\n</code></pre>\n"
},
{
"answer_id": 206433,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<h2>In General</h2>\n\n<p>The problem here is that you're calling a WordPress function within a PHP file where WordPress isn't loaded.</p>\n\n<p>Including WordPress in your <code>image.php</code> file might work if you include the post ID </p>\n\n<pre><code><img src=\"/wp-content/themes/v2/image.php?post_id=123\" />\n</code></pre>\n\n<p>But imagine if you have 100 images on a single page, then you would be running 101 instances of WordPress! </p>\n\n<p>You might try to hook into WordPress and run only minimized version of WordPress, but then we are still running PHP for each of those images.</p>\n\n<p>Another approach would be to avoid any WordPress calls in your <code>image.php</code> file and grab only the title text:</p>\n\n<pre><code><img src=\"/wp-content/themes/v2/image.php?title=Hello+World!\" />\n</code></pre>\n\n<p>But here the danger is that anyone could create an image with any kind of text. That's not good. You could add restrictions, like checking the referrer, but that might not be \"watertight\".</p>\n\n<p>Better approach might be to create the image files when the post title is modified. Then we can simply call the image file with:</p>\n\n<pre><code><img src=\"/wp-content/uploads/titles/image-123.png\" />\n</code></pre>\n\n<p>but with things like browser caching, we might need a cache buster:</p>\n\n<pre><code><img src=\"/wp-content/uploads/titles/image-123.png?last-modified=1445683693 \" />\n</code></pre>\n\n<p>We might also use the post title in the image file name:</p>\n\n<pre><code><img src=\"/wp-content/uploads/titles/image-hello-world.png\" />\n</code></pre>\n\n<p>The only thing here is we would need to generate those images for old posts. </p>\n\n<p>Let's take a closer look at the last mentioned approach.</p>\n\n<h2>Implementation</h2>\n\n<p>Let's assume we have the GD image package installed on our server. Then we could extend the <code>WP_Image_Editor_GD</code> class to our needs:</p>\n\n<pre><code>class WPSE_Image_Editor_GD extends WP_Image_Editor_GD\n{\n private $wpse_bgclr;\n private $wpse_txtclr;\n private $wpse_txt;\n\n public function wpse_new( $width = 0, $height = 0 ) \n {\n $this->image = imagecreate( $width, $height );\n return $this;\n }\n\n protected function wpse_color( $red = 0, $green = 0, $blue = 0 )\n {\n return imagecolorallocate( $this->image, (int) $red, (int) $green, (int) $blue );\n }\n\n public function wpse_textcolor( $red = 0, $green = 0, $blue = 0 )\n {\n $this->wpse_txtclr = $this->wpse_color( (int) $red, (int) $green, (int) $blue );\n return $this;\n }\n\n public function wpse_bgcolor( $red = 0, $green = 0, $blue = 0 )\n {\n $this->wpse_bgclr = $this->wpse_color( (int) $red, (int) $green, (int) $blue );\n return $this;\n }\n\n public function wpse_text( $text ) \n { \n $this->wpse_txt = imagestring( $this->image, 5, 0, 0, $text, $this->wpse_txtclr );\n return $this;\n }\n\n}\n</code></pre>\n\n<p>Here we prefix our methods with <code>wpse_</code> to avoid possible name collisions in the future.</p>\n\n<p>It's also handy to return <code>$this</code> for <em>chaining</em>.</p>\n\n<p>We can get the current upload path with:</p>\n\n<pre><code>$upload_dir = wp_upload_dir();\n</code></pre>\n\n<p>and to set the upload path for the generated title <em>.png</em> files, we could use:</p>\n\n<pre><code>$file = sprintf( '%s/wpse_titles/image-%s.png', \n $upload_dir['basedir'], \n strtolower( sanitize_file_name( $post->post_title ) ) \n); \n</code></pre>\n\n<p>This would save the <em>Hello World</em> title to the file:</p>\n\n<pre><code>/wp-content/uploads/wpse_titles/image-hello-world.png\n</code></pre>\n\n<p>We could use the <code>save_post_{$post_type}</code> hook to target a specific post type updates.</p>\n\n<p>But don't want to generate it on each update, so let's check if it's a file that already exists with:</p>\n\n<pre><code>if( is_file( $file ) )\n return;\n</code></pre>\n\n<p>Now we can use our custom class and create an instance:</p>\n\n<pre><code>$o = new WPSE_Image_Editor_GD;\n</code></pre>\n\n<p>and create an empty image object, color it, add the post title string to it and then save it:</p>\n\n<pre><code> $result = $o\n ->wpse_new( 300, 60 ) // Width x height = 300 x 60\n ->wpse_bgcolor( 0, 0, 255 ) // Background color as Blue\n ->wpse_textcolor( 255, 255, 0 ) // Text color as Yellow\n ->wpse_text( $post->post_title ) // Hello World\n ->save( $file, 'image/png' ); // Save it to image-helloworld.png\n</code></pre>\n\n<h2>Output Example</h2>\n\n<p>Here's an example how the <em>image-helloworld.png</em> image would look like:</p>\n\n<p><a href=\"https://i.stack.imgur.com/g337M.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/g337M.png\" alt=\"hello world\"></a></p>\n\n<h2>Demo plugin</h2>\n\n<p>Here we add it all together in a demo plugin:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: WPSE Title Images\n * Description: On post update, create a png file of the post title (/uploads/wpse-titles/)\n * Plugin Author: Birgir Erlendsson (birgire)\n * Plurin URI: http://wordpress.stackexchange.com/a/206433/26350\n * Version: 0.0.2\n */\nadd_action( 'save_post_post', function( $post_id, $post )\n{\n // Ignore auto save or revisions\n if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) )\n return;\n\n if( class_exists( 'WPSE_Image_Editor_GD' ) )\n return;\n\n // Get the current upload path \n $upload_dir = wp_upload_dir();\n\n // Generated file path\n $file = sprintf( \n '%s/wpse_titles/image-%s.png', \n $upload_dir['basedir'], \n sanitize_key( $post->post_title ) \n ); \n\n // Only create it once\n if( is_file( $file ) )\n return;\n\n // Load the WP_Image_Editor and WP_Image_Editor_GD classes \n require_once ABSPATH . WPINC . '/class-wp-image-editor.php';\n require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';\n\n // Our custom extension\n class WPSE_Image_Editor_GD extends WP_Image_Editor_GD\n {\n private $wpse_bgclr;\n private $wpse_txtclr;\n private $wpse_txt;\n\n public function wpse_new( $width = 0, $height = 0 ) \n {\n $this->image = imagecreate( $width, $height ); \n return $this;\n }\n\n protected function wpse_color( $red = 0, $green = 0, $blue = 0 )\n {\n return imagecolorallocate( $this->image, (int) $red, (int) $green, (int) $blue );\n }\n\n public function wpse_textcolor( $red = 0, $green = 0, $blue = 0 )\n {\n $this->wpse_txtclr = $this->wpse_color( (int) $red, (int) $green, (int) $blue ); \n return $this;\n }\n\n public function wpse_bgcolor( $red = 0, $green = 0, $blue = 0 )\n {\n $this->wpse_bgclr = $this->wpse_color( (int) $red, (int) $green, (int) $blue ); \n return $this;\n }\n\n public function wpse_text( $text ) \n { \n $this->wpse_txt = imagestring( $this->image, 5, 0, 0, $text, $this->wpse_txtclr );\n return $this;\n }\n\n } // end class\n\n // Generate and save the title as a .png file \n $o = new WPSE_Image_Editor_GD;\n\n $result = $o\n ->wpse_new( 300, 60 ) // Width x height = 300 x 60\n ->wpse_bgcolor( 0, 0, 255 ) // Background color as Blue\n ->wpse_textcolor( 255, 255, 0 ) // Text color as Yellow\n ->wpse_text( $post->post_title ) // Hello World\n ->save( $file, 'image/png' ); // Save it to image-helloworld.png\n\n}, 10, 3 );\n</code></pre>\n\n<p>We might then create our own template tag, to display the image for each post:</p>\n\n<pre><code>if( function_exists( 'wpse_title_image' ) )\n wpse_title_image( $default_url = '' );\n</code></pre>\n\n<p>Here's an example, but in a proper plugin structure, we should be able to remove the duplicated code presented here:</p>\n\n<pre><code>/**\n * Get the current post's title image \n *\n * @param string $default_url Default image url\n * @return string $html Html for the title image\n */\nfunction get_wpse_title_image( $default_url = '' )\n{\n $post = get_post();\n $upload_dir = wp_upload_dir();\n $dirname = 'wpse_titles';\n\n $file = sprintf( \n 'image-%s.png',\n strtolower( sanitize_file_name( $post->post_title ) ) \n );\n\n $file_path = sprintf( \n '%s/%s/%s',\n $upload_dir['basedir'], \n $dirname,\n $file\n ); \n\n $file_url = sprintf( \n '%s/%s/%s',\n $upload_dir['baseurl'], \n $dirname,\n $file\n ); \n\n if( is_file( $file_path ) && is_readable( $file_path ) )\n $url = $file_url;\n else\n $url = $default_url;\n\n return sprintf( \n '<img src=\"%s\" alt=\"%s\">', \n esc_url( $url ),\n esc_attr( $post->post_title )\n );\n}\n</code></pre>\n\n<p>Then you can define the following wrapper:</p>\n\n<pre><code>/**\n * Display the current post's title image \n *\n * @uses get_wpse_title_image()\n *\n * @param string $default_url Default image url\n * @return void\n */\nfunction wpse_title_image( $default_url = '' )\n{\n echo get_wpse_title_image( $default_url );\n}\n</code></pre>\n\n<h2>Notes</h2>\n\n<p>This demo could be extended further, like:</p>\n\n<ul>\n<li>take this into a proper plugin structure</li>\n<li>adjusting the handling of the <em>width</em> and <em>height</em> of each title image. </li>\n<li>auto generate images for all posts</li>\n<li>do this for other post types</li>\n<li>... etc ...</li>\n</ul>\n"
}
] |
2015/10/24
|
[
"https://wordpress.stackexchange.com/questions/206435",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81756/"
] |
I am changing hosting + domain name for my WordPress site. For example now if its hosted on 201.0.0.1/mysite and now I want to upload it to mysite.com. This is what I did
exported database from my cpanel
got all files from server using filezilla (public\_html folder that has Wordpress root folder as well)
set permalinks option to default and exported all content from existing site.
now planning to create a new database, setup wp-config.php and replace all files in public\_html files.
My question is after doing all this will I face any issues regarding page / posts or any other links means it may not happen that I may get some broken links after doing all this. Is there any extra step required with all this mentioned above or is it okay?
|
In General
----------
The problem here is that you're calling a WordPress function within a PHP file where WordPress isn't loaded.
Including WordPress in your `image.php` file might work if you include the post ID
```
<img src="/wp-content/themes/v2/image.php?post_id=123" />
```
But imagine if you have 100 images on a single page, then you would be running 101 instances of WordPress!
You might try to hook into WordPress and run only minimized version of WordPress, but then we are still running PHP for each of those images.
Another approach would be to avoid any WordPress calls in your `image.php` file and grab only the title text:
```
<img src="/wp-content/themes/v2/image.php?title=Hello+World!" />
```
But here the danger is that anyone could create an image with any kind of text. That's not good. You could add restrictions, like checking the referrer, but that might not be "watertight".
Better approach might be to create the image files when the post title is modified. Then we can simply call the image file with:
```
<img src="/wp-content/uploads/titles/image-123.png" />
```
but with things like browser caching, we might need a cache buster:
```
<img src="/wp-content/uploads/titles/image-123.png?last-modified=1445683693 " />
```
We might also use the post title in the image file name:
```
<img src="/wp-content/uploads/titles/image-hello-world.png" />
```
The only thing here is we would need to generate those images for old posts.
Let's take a closer look at the last mentioned approach.
Implementation
--------------
Let's assume we have the GD image package installed on our server. Then we could extend the `WP_Image_Editor_GD` class to our needs:
```
class WPSE_Image_Editor_GD extends WP_Image_Editor_GD
{
private $wpse_bgclr;
private $wpse_txtclr;
private $wpse_txt;
public function wpse_new( $width = 0, $height = 0 )
{
$this->image = imagecreate( $width, $height );
return $this;
}
protected function wpse_color( $red = 0, $green = 0, $blue = 0 )
{
return imagecolorallocate( $this->image, (int) $red, (int) $green, (int) $blue );
}
public function wpse_textcolor( $red = 0, $green = 0, $blue = 0 )
{
$this->wpse_txtclr = $this->wpse_color( (int) $red, (int) $green, (int) $blue );
return $this;
}
public function wpse_bgcolor( $red = 0, $green = 0, $blue = 0 )
{
$this->wpse_bgclr = $this->wpse_color( (int) $red, (int) $green, (int) $blue );
return $this;
}
public function wpse_text( $text )
{
$this->wpse_txt = imagestring( $this->image, 5, 0, 0, $text, $this->wpse_txtclr );
return $this;
}
}
```
Here we prefix our methods with `wpse_` to avoid possible name collisions in the future.
It's also handy to return `$this` for *chaining*.
We can get the current upload path with:
```
$upload_dir = wp_upload_dir();
```
and to set the upload path for the generated title *.png* files, we could use:
```
$file = sprintf( '%s/wpse_titles/image-%s.png',
$upload_dir['basedir'],
strtolower( sanitize_file_name( $post->post_title ) )
);
```
This would save the *Hello World* title to the file:
```
/wp-content/uploads/wpse_titles/image-hello-world.png
```
We could use the `save_post_{$post_type}` hook to target a specific post type updates.
But don't want to generate it on each update, so let's check if it's a file that already exists with:
```
if( is_file( $file ) )
return;
```
Now we can use our custom class and create an instance:
```
$o = new WPSE_Image_Editor_GD;
```
and create an empty image object, color it, add the post title string to it and then save it:
```
$result = $o
->wpse_new( 300, 60 ) // Width x height = 300 x 60
->wpse_bgcolor( 0, 0, 255 ) // Background color as Blue
->wpse_textcolor( 255, 255, 0 ) // Text color as Yellow
->wpse_text( $post->post_title ) // Hello World
->save( $file, 'image/png' ); // Save it to image-helloworld.png
```
Output Example
--------------
Here's an example how the *image-helloworld.png* image would look like:
[](https://i.stack.imgur.com/g337M.png)
Demo plugin
-----------
Here we add it all together in a demo plugin:
```
<?php
/**
* Plugin Name: WPSE Title Images
* Description: On post update, create a png file of the post title (/uploads/wpse-titles/)
* Plugin Author: Birgir Erlendsson (birgire)
* Plurin URI: http://wordpress.stackexchange.com/a/206433/26350
* Version: 0.0.2
*/
add_action( 'save_post_post', function( $post_id, $post )
{
// Ignore auto save or revisions
if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) )
return;
if( class_exists( 'WPSE_Image_Editor_GD' ) )
return;
// Get the current upload path
$upload_dir = wp_upload_dir();
// Generated file path
$file = sprintf(
'%s/wpse_titles/image-%s.png',
$upload_dir['basedir'],
sanitize_key( $post->post_title )
);
// Only create it once
if( is_file( $file ) )
return;
// Load the WP_Image_Editor and WP_Image_Editor_GD classes
require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
// Our custom extension
class WPSE_Image_Editor_GD extends WP_Image_Editor_GD
{
private $wpse_bgclr;
private $wpse_txtclr;
private $wpse_txt;
public function wpse_new( $width = 0, $height = 0 )
{
$this->image = imagecreate( $width, $height );
return $this;
}
protected function wpse_color( $red = 0, $green = 0, $blue = 0 )
{
return imagecolorallocate( $this->image, (int) $red, (int) $green, (int) $blue );
}
public function wpse_textcolor( $red = 0, $green = 0, $blue = 0 )
{
$this->wpse_txtclr = $this->wpse_color( (int) $red, (int) $green, (int) $blue );
return $this;
}
public function wpse_bgcolor( $red = 0, $green = 0, $blue = 0 )
{
$this->wpse_bgclr = $this->wpse_color( (int) $red, (int) $green, (int) $blue );
return $this;
}
public function wpse_text( $text )
{
$this->wpse_txt = imagestring( $this->image, 5, 0, 0, $text, $this->wpse_txtclr );
return $this;
}
} // end class
// Generate and save the title as a .png file
$o = new WPSE_Image_Editor_GD;
$result = $o
->wpse_new( 300, 60 ) // Width x height = 300 x 60
->wpse_bgcolor( 0, 0, 255 ) // Background color as Blue
->wpse_textcolor( 255, 255, 0 ) // Text color as Yellow
->wpse_text( $post->post_title ) // Hello World
->save( $file, 'image/png' ); // Save it to image-helloworld.png
}, 10, 3 );
```
We might then create our own template tag, to display the image for each post:
```
if( function_exists( 'wpse_title_image' ) )
wpse_title_image( $default_url = '' );
```
Here's an example, but in a proper plugin structure, we should be able to remove the duplicated code presented here:
```
/**
* Get the current post's title image
*
* @param string $default_url Default image url
* @return string $html Html for the title image
*/
function get_wpse_title_image( $default_url = '' )
{
$post = get_post();
$upload_dir = wp_upload_dir();
$dirname = 'wpse_titles';
$file = sprintf(
'image-%s.png',
strtolower( sanitize_file_name( $post->post_title ) )
);
$file_path = sprintf(
'%s/%s/%s',
$upload_dir['basedir'],
$dirname,
$file
);
$file_url = sprintf(
'%s/%s/%s',
$upload_dir['baseurl'],
$dirname,
$file
);
if( is_file( $file_path ) && is_readable( $file_path ) )
$url = $file_url;
else
$url = $default_url;
return sprintf(
'<img src="%s" alt="%s">',
esc_url( $url ),
esc_attr( $post->post_title )
);
}
```
Then you can define the following wrapper:
```
/**
* Display the current post's title image
*
* @uses get_wpse_title_image()
*
* @param string $default_url Default image url
* @return void
*/
function wpse_title_image( $default_url = '' )
{
echo get_wpse_title_image( $default_url );
}
```
Notes
-----
This demo could be extended further, like:
* take this into a proper plugin structure
* adjusting the handling of the *width* and *height* of each title image.
* auto generate images for all posts
* do this for other post types
* ... etc ...
|
206,455 |
<p>I want to create a user via a standalone script. I want an activation email to be sent out, in the same way that it is when a user is created from the Add User screen. An email is set out with a link to create the password. There is no password in the email.</p>
<p>There seem to be various functions for creating new users.</p>
<ul>
<li><a href="https://codex.wordpress.org/Function_Reference/wp_insert_user" rel="noreferrer">wp_insert_user</a> </li>
<li><a href="https://codex.wordpress.org/Function_Reference/wp_create_user" rel="noreferrer">wp_create_user</a></li>
<li>[register_new_user][3]</li>
</ul>
<p>There's also</p>
<ul>
<li>wp-admin/user-new.php</li>
</ul>
<p>Below is the code I have. It creates a new user, but it isn't the notification email. I've checked that wp-mail() and php mail() are working correctly. </p>
<p>I'm not sure that this is the right direction. I feel there might be an easier way to do it. If this is the right direction, any pointers on why the notification is not being sent?</p>
<p>Thanks.</p>
<pre><code><?php
define( 'SHORTINIT', true );
require_once( '/var/www/html/mysite/wp-load.php' );
require_once ('/var/www/html/mysite/wp-includes/user.php');
require_once ('/var/www/html/mysite/wp-includes/formatting.php');
require_once ('/var/www/html/mysite/wp-includes/capabilities.php');
require_once ('/var/www/html/mysite/wp-includes/pluggable.php');
require_once ('/var/www/html/mysite/wp-includes/kses.php');
require_once ('/var/www/html/mysite/wp-includes/meta.php');
function __() {}
wp_create_user ( 'testuser8', 'apsswd', '[email protected]' );
wp_new_user_notification ( testuser8,null,'both' );
?>
</code></pre>
|
[
{
"answer_id": 206458,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 3,
"selected": false,
"text": "<p>You should <a href=\"https://codex.wordpress.org/Function_Reference/wp_create_user\" rel=\"noreferrer\">read the codex page re wp_create_user</a>.</p>\n\n<p>You don't describe the context in which your code runs. \nYou shouldn't need all those <code>require_once</code> calls.</p>\n\n<p>Anyhow, in this line <code>wp_new_user_notification ( testuser8,null,'both' );</code> what is <code>testuser8</code> ? It's not a variable, it's not a string, it's just some text that probably throws an error. </p>\n\n<p>Try:</p>\n\n<pre><code>$user_id = wp_create_user ( 'testuser8', 'apsswd', '[email protected]' );\nif( is_wp_error( $user_id ) ) \n var_dump( $user_id );\nelse\n wp_new_user_notification ( $user_id, null,'both' );\n</code></pre>\n"
},
{
"answer_id": 245533,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 2,
"selected": false,
"text": "<p>Use WP-CLI's <a href=\"https://wp-cli.org/commands/user/create/\" rel=\"nofollow noreferrer\">User Create</a> and put in a script.</p>\n\n<blockquote>\n <p><code>wp user create</code> - Create a user.</p>\n</blockquote>\n\n<pre><code>$ wp user create testuser8 [email protected] --user_pass=apsswd--role=author --send-email\nSuccess: Created user 3.\n</code></pre>\n"
}
] |
2015/10/24
|
[
"https://wordpress.stackexchange.com/questions/206455",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82453/"
] |
I want to create a user via a standalone script. I want an activation email to be sent out, in the same way that it is when a user is created from the Add User screen. An email is set out with a link to create the password. There is no password in the email.
There seem to be various functions for creating new users.
* [wp\_insert\_user](https://codex.wordpress.org/Function_Reference/wp_insert_user)
* [wp\_create\_user](https://codex.wordpress.org/Function_Reference/wp_create_user)
* [register\_new\_user][3]
There's also
* wp-admin/user-new.php
Below is the code I have. It creates a new user, but it isn't the notification email. I've checked that wp-mail() and php mail() are working correctly.
I'm not sure that this is the right direction. I feel there might be an easier way to do it. If this is the right direction, any pointers on why the notification is not being sent?
Thanks.
```
<?php
define( 'SHORTINIT', true );
require_once( '/var/www/html/mysite/wp-load.php' );
require_once ('/var/www/html/mysite/wp-includes/user.php');
require_once ('/var/www/html/mysite/wp-includes/formatting.php');
require_once ('/var/www/html/mysite/wp-includes/capabilities.php');
require_once ('/var/www/html/mysite/wp-includes/pluggable.php');
require_once ('/var/www/html/mysite/wp-includes/kses.php');
require_once ('/var/www/html/mysite/wp-includes/meta.php');
function __() {}
wp_create_user ( 'testuser8', 'apsswd', '[email protected]' );
wp_new_user_notification ( testuser8,null,'both' );
?>
```
|
You should [read the codex page re wp\_create\_user](https://codex.wordpress.org/Function_Reference/wp_create_user).
You don't describe the context in which your code runs.
You shouldn't need all those `require_once` calls.
Anyhow, in this line `wp_new_user_notification ( testuser8,null,'both' );` what is `testuser8` ? It's not a variable, it's not a string, it's just some text that probably throws an error.
Try:
```
$user_id = wp_create_user ( 'testuser8', 'apsswd', '[email protected]' );
if( is_wp_error( $user_id ) )
var_dump( $user_id );
else
wp_new_user_notification ( $user_id, null,'both' );
```
|
206,465 |
<p>I'm making my first WordPress theme from scratch, and I currently have two pages: <code>index</code>, and <code>events</code>. The <code>index</code> is static and the <code>events.php</code> is dynamic (loaded with latest events displayed by the title and thumbnail).</p>
<p>I also have two posts; one being the default Hello World, and the second made by me, some text and about 9 images.</p>
<p>The problem is when I try to run the loop, I only get one window with the title of the page:</p>
<pre><code>get_header();
/*
Template Name: eventy
*/
?>
<div id="innerContainer">
<h2 style="color: #000c14">EVENTY</h2>
<div id="GALERIA">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="gelement">
<a href="<?php the_permalink() ?>">
<div class="gimg"><?php the_post_thumbnail(); ?></div>
<div class="gtitle"> <p><?php the_title() ;?></p></div>
</a>
</div><!--GELEMENT END-->
<?php endwhile; else: ?>
<p>Sorry, no posts to list</p>
<?php endif; ?>
</div><!--GLAERIA END -->
<div id="zmianastrony">
<p style="text-align: center; color: #000c14;">
<a href="#" style="color: #000c14;">-Poprzednia</a>
<a href="#" style="color: #000c14;">NastΔpna-</a>
</p>
</div>
</div> <!-- inner container END -->
<?php get_footer();
</code></pre>
<p>What could be the problem here?</p>
|
[
{
"answer_id": 206458,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 3,
"selected": false,
"text": "<p>You should <a href=\"https://codex.wordpress.org/Function_Reference/wp_create_user\" rel=\"noreferrer\">read the codex page re wp_create_user</a>.</p>\n\n<p>You don't describe the context in which your code runs. \nYou shouldn't need all those <code>require_once</code> calls.</p>\n\n<p>Anyhow, in this line <code>wp_new_user_notification ( testuser8,null,'both' );</code> what is <code>testuser8</code> ? It's not a variable, it's not a string, it's just some text that probably throws an error. </p>\n\n<p>Try:</p>\n\n<pre><code>$user_id = wp_create_user ( 'testuser8', 'apsswd', '[email protected]' );\nif( is_wp_error( $user_id ) ) \n var_dump( $user_id );\nelse\n wp_new_user_notification ( $user_id, null,'both' );\n</code></pre>\n"
},
{
"answer_id": 245533,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 2,
"selected": false,
"text": "<p>Use WP-CLI's <a href=\"https://wp-cli.org/commands/user/create/\" rel=\"nofollow noreferrer\">User Create</a> and put in a script.</p>\n\n<blockquote>\n <p><code>wp user create</code> - Create a user.</p>\n</blockquote>\n\n<pre><code>$ wp user create testuser8 [email protected] --user_pass=apsswd--role=author --send-email\nSuccess: Created user 3.\n</code></pre>\n"
}
] |
2015/10/24
|
[
"https://wordpress.stackexchange.com/questions/206465",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80982/"
] |
I'm making my first WordPress theme from scratch, and I currently have two pages: `index`, and `events`. The `index` is static and the `events.php` is dynamic (loaded with latest events displayed by the title and thumbnail).
I also have two posts; one being the default Hello World, and the second made by me, some text and about 9 images.
The problem is when I try to run the loop, I only get one window with the title of the page:
```
get_header();
/*
Template Name: eventy
*/
?>
<div id="innerContainer">
<h2 style="color: #000c14">EVENTY</h2>
<div id="GALERIA">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="gelement">
<a href="<?php the_permalink() ?>">
<div class="gimg"><?php the_post_thumbnail(); ?></div>
<div class="gtitle"> <p><?php the_title() ;?></p></div>
</a>
</div><!--GELEMENT END-->
<?php endwhile; else: ?>
<p>Sorry, no posts to list</p>
<?php endif; ?>
</div><!--GLAERIA END -->
<div id="zmianastrony">
<p style="text-align: center; color: #000c14;">
<a href="#" style="color: #000c14;">-Poprzednia</a>
<a href="#" style="color: #000c14;">NastΔpna-</a>
</p>
</div>
</div> <!-- inner container END -->
<?php get_footer();
```
What could be the problem here?
|
You should [read the codex page re wp\_create\_user](https://codex.wordpress.org/Function_Reference/wp_create_user).
You don't describe the context in which your code runs.
You shouldn't need all those `require_once` calls.
Anyhow, in this line `wp_new_user_notification ( testuser8,null,'both' );` what is `testuser8` ? It's not a variable, it's not a string, it's just some text that probably throws an error.
Try:
```
$user_id = wp_create_user ( 'testuser8', 'apsswd', '[email protected]' );
if( is_wp_error( $user_id ) )
var_dump( $user_id );
else
wp_new_user_notification ( $user_id, null,'both' );
```
|
206,468 |
<p>I am working on a Custom Nav Walker and I want to use Description field in wordpress menu in my theme. </p>
<p>The field works fine as far as for First Level Menu items but when I add something in sub-menu items' description fields, nothing outputs. </p>
<p>I am using following custom nav walker function:</p>
<pre><code>class description_walker extends Walker_Nav_Menu
{
function start_el(&$output, $item, $depth, $args)
{
global $wp_query;
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$class_names = $value = '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
$class_names = ' class="'. esc_attr( $class_names ) . '"';
$output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>';
$attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
$attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
$attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
$attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';
$prepend = '<strong>';
$append = '</strong>';
$description = ! empty( $item->description ) ? '<img src="'.esc_attr( $item->description ).'" />' : '';
if($depth != 0)
{
$description = $append = $prepend = "";
}
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
$item_output .= $args->link_before .$prepend.apply_filters( 'the_title', $item->title, $item->ID ).$append;
$item_output .= $description.$args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
}
</code></pre>
<p>Any help would be highly appreciated!</p>
<p>Thanks</p>
<p>Abu</p>
|
[
{
"answer_id": 206472,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 1,
"selected": true,
"text": "<p>You are setting your <code>$description</code> to an empty string for any menu item except the top one:</p>\n\n<pre><code> if($depth != 0)\n {\n $description = $append = $prepend = \"\";\n }\n</code></pre>\n\n<p>Thus, you get no output.</p>\n"
},
{
"answer_id": 206473,
"author": "Dejo Dekic",
"author_id": 20941,
"author_profile": "https://wordpress.stackexchange.com/users/20941",
"pm_score": 1,
"selected": false,
"text": "<p>So much code for such a simple thing:) Add this code to your functions.php.</p>\n\n<pre><code> //Adds description to our menu\n /**\n * Display descriptions in main navigation.\n *\n * CREDIT: Twenty Fifteen 1.0\n * See: http://wordpress.stackexchange.com/questions/14037/menu-items-description-custom-walker-for-wp-nav-menu\n * @param string $item_output The menu item output.\n * @param WP_Post $item Menu item object.\n * @param int $depth Depth of the menu.\n * @param array $args wp_nav_menu() arguments.\n * @return string Menu item with possible description.\n */\n function add_nav_description( $item_output, $item, $depth, $args ) {\nif ( 'main-menu' == $args->theme_location && $item->description ) {\n $item_output = str_replace( $args->link_after . '</a>', '<div class=\"menu-item-description\">' . esc_html( $item->description ) . '</div>' . $args->link_after . '</a>', $item_output );\n}\n\nreturn $item_output;\n}\nadd_filter( 'walker_nav_menu_start_el', 'add_nav_description', 10, 4 );\n</code></pre>\n"
}
] |
2015/10/24
|
[
"https://wordpress.stackexchange.com/questions/206468",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58787/"
] |
I am working on a Custom Nav Walker and I want to use Description field in wordpress menu in my theme.
The field works fine as far as for First Level Menu items but when I add something in sub-menu items' description fields, nothing outputs.
I am using following custom nav walker function:
```
class description_walker extends Walker_Nav_Menu
{
function start_el(&$output, $item, $depth, $args)
{
global $wp_query;
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$class_names = $value = '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
$class_names = ' class="'. esc_attr( $class_names ) . '"';
$output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>';
$attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
$attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
$attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
$attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';
$prepend = '<strong>';
$append = '</strong>';
$description = ! empty( $item->description ) ? '<img src="'.esc_attr( $item->description ).'" />' : '';
if($depth != 0)
{
$description = $append = $prepend = "";
}
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
$item_output .= $args->link_before .$prepend.apply_filters( 'the_title', $item->title, $item->ID ).$append;
$item_output .= $description.$args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
}
```
Any help would be highly appreciated!
Thanks
Abu
|
You are setting your `$description` to an empty string for any menu item except the top one:
```
if($depth != 0)
{
$description = $append = $prepend = "";
}
```
Thus, you get no output.
|
206,471 |
<p>Here is a the code snippet:</p>
<pre><code> add_action( 'admin_menu', 'travel_site' );
function travel_site(){
add_menu_page( 'Travel Site Menu', 'Travel Site', 'manage_options', 'travel-site-menu', 'ts_admin_main_page' );
add_submenu_page("travel-site-menu","View Travel Requests","View Travel Requests","manage_options","ts-view-travel-requests","ts_admin_vtr_page");
}
function ts_admin_main_page(){
echo '<div class="wrap">';
echo '<p>Testing main travel site menu page</p>';
echo '</div>';
}
function ts_admin_vtr_page(){
echo '<div class="wrap">';
echo '<p>Testing view travel requests</p>';
echo '</div>';
}
</code></pre>
<p>The problem is when adding the sub menu, the name of the top level menu("Travel Site") creates itself as a sub-level menu. See image: <a href="https://i.stack.imgur.com/BZako.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BZako.png" alt="enter image description here"></a></p>
<p>Basically I don't want "Travel Site" sub-menu under the main menu "Travel Site", how do i remove the submenu "Travel Site"?</p>
|
[
{
"answer_id": 206476,
"author": "chrisguitarguy",
"author_id": 6035,
"author_profile": "https://wordpress.stackexchange.com/users/6035",
"pm_score": 2,
"selected": false,
"text": "<p>There's not really a good way to do this. Checkout the <a href=\"https://github.com/WordPress/WordPress/blob/4.3.1/wp-admin/menu-header.php#L57\" rel=\"nofollow\"><code>_wp_menu_output</code></a> function. It's where all the work gets done for the menu output. See that <code>$submenu_as_parent</code> parameter and <a href=\"https://github.com/WordPress/WordPress/blob/4.3.1/wp-admin/menu-header.php#L133-L156\" rel=\"nofollow\">how it's used</a>? Setting that to false produces the result you want, but there's no filters to actually make that work. There is an <a href=\"https://core.trac.wordpress.org/ticket/19085\" rel=\"nofollow\">open ticket</a> on the matter, but no action has really been taken for over a year. Short of editting a core file (bad idea), you're not going to solve this without some output buffering and a very fragile solution.</p>\n"
},
{
"answer_id": 310368,
"author": "dbmpls",
"author_id": 97681,
"author_profile": "https://wordpress.stackexchange.com/users/97681",
"pm_score": 2,
"selected": true,
"text": "<p>Effectively you can do this by adding a sublevel item with the same menu slug as the top level, while changing the submenu item title. This avoids the look of duplicate menu items, even though the destination of the top level, and the first sub menu item are the same.</p>\n\n<p>You have to have at least two sub menu items, and one will be a duplicate destination as your top level menu item.</p>\n\n<p>For example:</p>\n\n<pre><code>add_action( 'admin_menu', 'add_travel_menu' );\nfunction add_travel_menu() {\n add_menu_page('Travel Site Menu', 'Travel Site', 'manage_options', 'travel-site-menu', 'ts_admin_main_page');\n add_submenu_page('travel-site-menu', 'Travel Site', 'View Travel Site', 'manage_options', 'travel-site-menu', 'ts_admin_main_page');\n add_submenu_page('travel-site-menu', 'View Travel Requests', 'View Travel Requests', 'manage_options', 'ts-view-travel-requests', 'ts_admin_main_page');\n}\nfunction ts_admin_main_page() {\n if ( !current_user_can( 'manage_options' ) ) {\n wp_die( __( 'You do not have sufficient permissions to access this page.' ) );\n }\n echo '<div class=\"wrap\">';\n echo '<p>Here is where the form would go if I actually had options.</p>';\n echo '</div>';\n}\n</code></pre>\n\n<p>This would create the Following Menu:</p>\n\n<ul>\n<li>Travel Site -> travel-site-menu\n\n<ul>\n<li>View Travel Site -> travel-site-menu</li>\n<li>View Travel Requests -> ts-view-travel-requests </li>\n</ul></li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/I33zc.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/I33zc.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>The function ts_admin_main_page actually creates the page that will be the destination for \"Travel Site\" and \"View Travel Site\". You would need to create the the similar function \"ts_admin_vtr_page\" that will create the sub page destination for \"View Travel Requests\". </p>\n"
}
] |
2015/10/24
|
[
"https://wordpress.stackexchange.com/questions/206471",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9390/"
] |
Here is a the code snippet:
```
add_action( 'admin_menu', 'travel_site' );
function travel_site(){
add_menu_page( 'Travel Site Menu', 'Travel Site', 'manage_options', 'travel-site-menu', 'ts_admin_main_page' );
add_submenu_page("travel-site-menu","View Travel Requests","View Travel Requests","manage_options","ts-view-travel-requests","ts_admin_vtr_page");
}
function ts_admin_main_page(){
echo '<div class="wrap">';
echo '<p>Testing main travel site menu page</p>';
echo '</div>';
}
function ts_admin_vtr_page(){
echo '<div class="wrap">';
echo '<p>Testing view travel requests</p>';
echo '</div>';
}
```
The problem is when adding the sub menu, the name of the top level menu("Travel Site") creates itself as a sub-level menu. See image: [](https://i.stack.imgur.com/BZako.png)
Basically I don't want "Travel Site" sub-menu under the main menu "Travel Site", how do i remove the submenu "Travel Site"?
|
Effectively you can do this by adding a sublevel item with the same menu slug as the top level, while changing the submenu item title. This avoids the look of duplicate menu items, even though the destination of the top level, and the first sub menu item are the same.
You have to have at least two sub menu items, and one will be a duplicate destination as your top level menu item.
For example:
```
add_action( 'admin_menu', 'add_travel_menu' );
function add_travel_menu() {
add_menu_page('Travel Site Menu', 'Travel Site', 'manage_options', 'travel-site-menu', 'ts_admin_main_page');
add_submenu_page('travel-site-menu', 'Travel Site', 'View Travel Site', 'manage_options', 'travel-site-menu', 'ts_admin_main_page');
add_submenu_page('travel-site-menu', 'View Travel Requests', 'View Travel Requests', 'manage_options', 'ts-view-travel-requests', 'ts_admin_main_page');
}
function ts_admin_main_page() {
if ( !current_user_can( 'manage_options' ) ) {
wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
}
echo '<div class="wrap">';
echo '<p>Here is where the form would go if I actually had options.</p>';
echo '</div>';
}
```
This would create the Following Menu:
* Travel Site -> travel-site-menu
+ View Travel Site -> travel-site-menu
+ View Travel Requests -> ts-view-travel-requests
[](https://i.stack.imgur.com/I33zc.jpg)
The function ts\_admin\_main\_page actually creates the page that will be the destination for "Travel Site" and "View Travel Site". You would need to create the the similar function "ts\_admin\_vtr\_page" that will create the sub page destination for "View Travel Requests".
|
206,485 |
<p>I'm working on a contact form for a website using an jQuery Ajax call method that then uses WordPress's building in admin-ajax.php to submit the form's values, send them to an email address via wp_mail and then, if successful, send back an array through json_encode. The form works and the email sends but the success data isn't send after and the Ajax :success function doesn't initiate.</p>
<p>This has worked on other sites and I'm not sure why it's not working on this site. It send the email, just my jQuery method gets no success callback.</p>
<p>Here's what I've been using.</p>
<p>jQuery </p>
<pre><code>(document).ready(function($){
$.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z\s]+$/i.test(value);
}, "Only alphabetical characters");
$.validator.addMethod("phoneNum", function(value, element) {
return this.optional(element) || /^[0-9\-\s]+$/i.test(value);
}, "Phone number can only be number and dashes.");
$("#contact-form").validate({
rules: {
name: {
required:true,
lettersonly: true
},
email: {
required: true,
email: true
},
phone: {
phoneNum: true,
},
message: {
required:true
}
},
messages: {
name: {
required: "Please enter your name.",
lettersonly: "Needs to be letters, no numbers please."
},
email: {
required: "Please enter your email adress.",
email: "Please enter your valid email adress."
},
phone: {
},
message:{
required: "Please enter a message.",
}
},
submitHandler: function(form) {
$('#contact-msg').html('<p class="ajaxLoader">Sending Email...</p>');
$.ajax ({
type: 'POST',
url: ajax_object.ajax_url,
data: $('#contact-form').serialize(),
dataType: 'json',
success: function(response) {
if (response.status == 'success') {
$('#contact-form')[0].reset();
}
$('#contact-msg').html(response.errmessage);
}
});
}
});
});
</code></pre>
<p>Function.php</p>
<pre><code>// CONTACT FORM SCRIPTS
function contactform_add_script() {
wp_enqueue_script( 'contactform-script', get_template_directory_uri().'/assets/js/contact_me.js', array('jquery') , null, true);
wp_localize_script( 'contactform-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', 'contactform_add_script');
// CONTACT FORM PROCESSING
function ajax_contactform_action_callback() {
$error = '';
$status = 'error';
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])) {
$error = 'All fields are required to enter.';
} else {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$number = filter_var($_POST['phone'], FILTER_SANITIZE_NUMBER_INT);
// $treatments = filter_var($_POST['treatments'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$subject = 'A message from St. Romain Interiors\'s contact form.';
$message .= PHP_EOL.'Sender\'s name: '.$name;
$message .= PHP_EOL.'Phone number: '.$number;
$message .= PHP_EOL.'E-mail address: '.$email;
$message .= PHP_EOL.'Message: '.stripslashes($_POST['message']);
$sendmsg = "Thanks for the message! We will respond as soon as possible.";
$to = '[email protected]'; // If you like change this email address
// replace "[email protected]" with your real email address
$header .= 'Reply-To: '.$email.PHP_EOL;
if ( wp_mail($to, $subject, $message, $header) ) {
$status = 'success';
$error = $sendmsg;
} else {
$error = 'Some errors occurred.';
}
}
$resp = array('status' => $status, 'errmessage' => $error);
header( "Content-Type: application/json" );
echo json_encode($resp);
die();
}
add_action( 'wp_ajax_contactform_action', 'ajax_contactform_action_callback' );
add_action( 'wp_ajax_nopriv_contactform_action', 'ajax_contactform_action_callback' );
</code></pre>
<p>UPDATE! </p>
<p>If I replace the submitHandler with this it returns the sentence, but now the email is never sent... </p>
<pre><code> submitHandler: function(form) {
$('#contact-msg').html('<p class="ajaxLoader">Sending Email...</p>');
$.ajax ({
type: 'POST',
url: ajax_object.ajax_url,
data: { action: "contactform_action",
values: $('#contact-form').serialize() },
dataType: 'json',
success: function(response) {
$('#contact-msg').html('<p>Thanks for the message!</p>');
}
});
}
</code></pre>
<p>UPDATE #2</p>
<p>I replaced the success function with the original from the first post, but kept the data values you suggested and it's doing the same old thing, sending the email but not sending a success callback. On Mozilla Firebug I was able to find this information in the Response Headers panel.</p>
<pre><code>X-Robots-Tag: noindex
X-Powered-By: PHP/5.6.14
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
Transfer-Encoding: chunked
Server: Apache
Pragma: no-cache
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Date: Mon, 26 Oct 2015 06:13:54 GMT
Content-Type: application/json
Cache-Control: no-cache, must-revalidate, max-age=0
</code></pre>
<p>UPDATE #3</p>
<p>Here's the response I see in Firebug</p>
<pre><code><br />
<b>Notice</b>: Undefined index: name in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>156</b><br />
<br />
<b>Notice</b>: Undefined index: email in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>157</b><br />
<br />
<b>Notice</b>: Undefined index: phone in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>158</b><br />
<br />
<b>Notice</b>: Undefined variable: message in<b>/home/theski/public_html/stromain/wp-content/themes
/stromain/functions.php</b> on line <b>161</b><br />
<br />
<b>Notice</b>: Undefined index: message in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>165</b><br />
<br />
<b>Notice</b>: Undefined variable: header in <b>/home/theski/public_html/stromain/wp-content/themes
/stromain/functions.php</b> on line <b>171</b><br />
{"status":"success","errmessage":"Thanks for the message! We will respond as soon as possible."}
</code></pre>
|
[
{
"answer_id": 206476,
"author": "chrisguitarguy",
"author_id": 6035,
"author_profile": "https://wordpress.stackexchange.com/users/6035",
"pm_score": 2,
"selected": false,
"text": "<p>There's not really a good way to do this. Checkout the <a href=\"https://github.com/WordPress/WordPress/blob/4.3.1/wp-admin/menu-header.php#L57\" rel=\"nofollow\"><code>_wp_menu_output</code></a> function. It's where all the work gets done for the menu output. See that <code>$submenu_as_parent</code> parameter and <a href=\"https://github.com/WordPress/WordPress/blob/4.3.1/wp-admin/menu-header.php#L133-L156\" rel=\"nofollow\">how it's used</a>? Setting that to false produces the result you want, but there's no filters to actually make that work. There is an <a href=\"https://core.trac.wordpress.org/ticket/19085\" rel=\"nofollow\">open ticket</a> on the matter, but no action has really been taken for over a year. Short of editting a core file (bad idea), you're not going to solve this without some output buffering and a very fragile solution.</p>\n"
},
{
"answer_id": 310368,
"author": "dbmpls",
"author_id": 97681,
"author_profile": "https://wordpress.stackexchange.com/users/97681",
"pm_score": 2,
"selected": true,
"text": "<p>Effectively you can do this by adding a sublevel item with the same menu slug as the top level, while changing the submenu item title. This avoids the look of duplicate menu items, even though the destination of the top level, and the first sub menu item are the same.</p>\n\n<p>You have to have at least two sub menu items, and one will be a duplicate destination as your top level menu item.</p>\n\n<p>For example:</p>\n\n<pre><code>add_action( 'admin_menu', 'add_travel_menu' );\nfunction add_travel_menu() {\n add_menu_page('Travel Site Menu', 'Travel Site', 'manage_options', 'travel-site-menu', 'ts_admin_main_page');\n add_submenu_page('travel-site-menu', 'Travel Site', 'View Travel Site', 'manage_options', 'travel-site-menu', 'ts_admin_main_page');\n add_submenu_page('travel-site-menu', 'View Travel Requests', 'View Travel Requests', 'manage_options', 'ts-view-travel-requests', 'ts_admin_main_page');\n}\nfunction ts_admin_main_page() {\n if ( !current_user_can( 'manage_options' ) ) {\n wp_die( __( 'You do not have sufficient permissions to access this page.' ) );\n }\n echo '<div class=\"wrap\">';\n echo '<p>Here is where the form would go if I actually had options.</p>';\n echo '</div>';\n}\n</code></pre>\n\n<p>This would create the Following Menu:</p>\n\n<ul>\n<li>Travel Site -> travel-site-menu\n\n<ul>\n<li>View Travel Site -> travel-site-menu</li>\n<li>View Travel Requests -> ts-view-travel-requests </li>\n</ul></li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/I33zc.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/I33zc.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>The function ts_admin_main_page actually creates the page that will be the destination for \"Travel Site\" and \"View Travel Site\". You would need to create the the similar function \"ts_admin_vtr_page\" that will create the sub page destination for \"View Travel Requests\". </p>\n"
}
] |
2015/10/25
|
[
"https://wordpress.stackexchange.com/questions/206485",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78415/"
] |
I'm working on a contact form for a website using an jQuery Ajax call method that then uses WordPress's building in admin-ajax.php to submit the form's values, send them to an email address via wp\_mail and then, if successful, send back an array through json\_encode. The form works and the email sends but the success data isn't send after and the Ajax :success function doesn't initiate.
This has worked on other sites and I'm not sure why it's not working on this site. It send the email, just my jQuery method gets no success callback.
Here's what I've been using.
jQuery
```
(document).ready(function($){
$.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z\s]+$/i.test(value);
}, "Only alphabetical characters");
$.validator.addMethod("phoneNum", function(value, element) {
return this.optional(element) || /^[0-9\-\s]+$/i.test(value);
}, "Phone number can only be number and dashes.");
$("#contact-form").validate({
rules: {
name: {
required:true,
lettersonly: true
},
email: {
required: true,
email: true
},
phone: {
phoneNum: true,
},
message: {
required:true
}
},
messages: {
name: {
required: "Please enter your name.",
lettersonly: "Needs to be letters, no numbers please."
},
email: {
required: "Please enter your email adress.",
email: "Please enter your valid email adress."
},
phone: {
},
message:{
required: "Please enter a message.",
}
},
submitHandler: function(form) {
$('#contact-msg').html('<p class="ajaxLoader">Sending Email...</p>');
$.ajax ({
type: 'POST',
url: ajax_object.ajax_url,
data: $('#contact-form').serialize(),
dataType: 'json',
success: function(response) {
if (response.status == 'success') {
$('#contact-form')[0].reset();
}
$('#contact-msg').html(response.errmessage);
}
});
}
});
});
```
Function.php
```
// CONTACT FORM SCRIPTS
function contactform_add_script() {
wp_enqueue_script( 'contactform-script', get_template_directory_uri().'/assets/js/contact_me.js', array('jquery') , null, true);
wp_localize_script( 'contactform-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', 'contactform_add_script');
// CONTACT FORM PROCESSING
function ajax_contactform_action_callback() {
$error = '';
$status = 'error';
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])) {
$error = 'All fields are required to enter.';
} else {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$number = filter_var($_POST['phone'], FILTER_SANITIZE_NUMBER_INT);
// $treatments = filter_var($_POST['treatments'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$subject = 'A message from St. Romain Interiors\'s contact form.';
$message .= PHP_EOL.'Sender\'s name: '.$name;
$message .= PHP_EOL.'Phone number: '.$number;
$message .= PHP_EOL.'E-mail address: '.$email;
$message .= PHP_EOL.'Message: '.stripslashes($_POST['message']);
$sendmsg = "Thanks for the message! We will respond as soon as possible.";
$to = '[email protected]'; // If you like change this email address
// replace "[email protected]" with your real email address
$header .= 'Reply-To: '.$email.PHP_EOL;
if ( wp_mail($to, $subject, $message, $header) ) {
$status = 'success';
$error = $sendmsg;
} else {
$error = 'Some errors occurred.';
}
}
$resp = array('status' => $status, 'errmessage' => $error);
header( "Content-Type: application/json" );
echo json_encode($resp);
die();
}
add_action( 'wp_ajax_contactform_action', 'ajax_contactform_action_callback' );
add_action( 'wp_ajax_nopriv_contactform_action', 'ajax_contactform_action_callback' );
```
UPDATE!
If I replace the submitHandler with this it returns the sentence, but now the email is never sent...
```
submitHandler: function(form) {
$('#contact-msg').html('<p class="ajaxLoader">Sending Email...</p>');
$.ajax ({
type: 'POST',
url: ajax_object.ajax_url,
data: { action: "contactform_action",
values: $('#contact-form').serialize() },
dataType: 'json',
success: function(response) {
$('#contact-msg').html('<p>Thanks for the message!</p>');
}
});
}
```
UPDATE #2
I replaced the success function with the original from the first post, but kept the data values you suggested and it's doing the same old thing, sending the email but not sending a success callback. On Mozilla Firebug I was able to find this information in the Response Headers panel.
```
X-Robots-Tag: noindex
X-Powered-By: PHP/5.6.14
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
Transfer-Encoding: chunked
Server: Apache
Pragma: no-cache
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Date: Mon, 26 Oct 2015 06:13:54 GMT
Content-Type: application/json
Cache-Control: no-cache, must-revalidate, max-age=0
```
UPDATE #3
Here's the response I see in Firebug
```
<br />
<b>Notice</b>: Undefined index: name in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>156</b><br />
<br />
<b>Notice</b>: Undefined index: email in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>157</b><br />
<br />
<b>Notice</b>: Undefined index: phone in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>158</b><br />
<br />
<b>Notice</b>: Undefined variable: message in<b>/home/theski/public_html/stromain/wp-content/themes
/stromain/functions.php</b> on line <b>161</b><br />
<br />
<b>Notice</b>: Undefined index: message in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>165</b><br />
<br />
<b>Notice</b>: Undefined variable: header in <b>/home/theski/public_html/stromain/wp-content/themes
/stromain/functions.php</b> on line <b>171</b><br />
{"status":"success","errmessage":"Thanks for the message! We will respond as soon as possible."}
```
|
Effectively you can do this by adding a sublevel item with the same menu slug as the top level, while changing the submenu item title. This avoids the look of duplicate menu items, even though the destination of the top level, and the first sub menu item are the same.
You have to have at least two sub menu items, and one will be a duplicate destination as your top level menu item.
For example:
```
add_action( 'admin_menu', 'add_travel_menu' );
function add_travel_menu() {
add_menu_page('Travel Site Menu', 'Travel Site', 'manage_options', 'travel-site-menu', 'ts_admin_main_page');
add_submenu_page('travel-site-menu', 'Travel Site', 'View Travel Site', 'manage_options', 'travel-site-menu', 'ts_admin_main_page');
add_submenu_page('travel-site-menu', 'View Travel Requests', 'View Travel Requests', 'manage_options', 'ts-view-travel-requests', 'ts_admin_main_page');
}
function ts_admin_main_page() {
if ( !current_user_can( 'manage_options' ) ) {
wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
}
echo '<div class="wrap">';
echo '<p>Here is where the form would go if I actually had options.</p>';
echo '</div>';
}
```
This would create the Following Menu:
* Travel Site -> travel-site-menu
+ View Travel Site -> travel-site-menu
+ View Travel Requests -> ts-view-travel-requests
[](https://i.stack.imgur.com/I33zc.jpg)
The function ts\_admin\_main\_page actually creates the page that will be the destination for "Travel Site" and "View Travel Site". You would need to create the the similar function "ts\_admin\_vtr\_page" that will create the sub page destination for "View Travel Requests".
|
206,509 |
<p>Is there a standard way to get all the registered sizes of the featured images?
One can register different sizes with <code>add_image_size()</code>.
What I need, is to get all the sizes of a featured image of a post.
Something like this:</p>
<p>$sizes = get_post_feature_image_sizes($postid);</p>
<p>...which will return an array of objects like this (here in JSON format):</p>
<pre><code>[
{width: 200, height: 300, url: 'http://.........../wp-content/uploads/2015/10/file-200x300.jpg'},
{width: 300, height: 400, url: 'http://.........../wp-content/uploads/2015/10/file.jpg'},
]
</code></pre>
<p>Is there anything like this, or I will have to scan all the upload folder file names with regex?</p>
|
[
{
"answer_id": 206534,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 5,
"selected": true,
"text": "<p>I don't remember a function that will do precisely that, but it is easily achieved with API overall:</p>\n\n<ol>\n<li>Retrieve attachment ID with <a href=\"https://developer.wordpress.org/reference/functions/get_post_thumbnail_id/\" rel=\"noreferrer\"><code>get_post_thumbnail_id()</code></a></li>\n<li>Retrieve available sizes with <a href=\"https://developer.wordpress.org/reference/functions/get_intermediate_image_sizes/\" rel=\"noreferrer\"><code>get_intermediate_image_sizes()</code></a></li>\n<li>For each size use <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"noreferrer\"><code>wp_get_attachment_image_src()</code></a>, which gives precisely data you need (URL and dimensions).</li>\n</ol>\n"
},
{
"answer_id": 206587,
"author": "Ajay Khandal",
"author_id": 82505,
"author_profile": "https://wordpress.stackexchange.com/users/82505",
"pm_score": 1,
"selected": false,
"text": "<p>To get image according to size you can use wordpres pre-defined function that is <code>the_post_thumbnail( $size, $attr )</code>.</p>\n\n<p>you can use predefined media sizes.</p>\n\n<pre><code>the_post_thumbnail(); \n\nthe_post_thumbnail( 'thumbnail' ); // Thumbnail (default 150px x 150px max)\nthe_post_thumbnail( 'medium' ); // Medium resolution (default 300px x 300px max)\nthe_post_thumbnail( 'large' ); // Large resolution (default 640px x 640px max)\nthe_post_thumbnail( 'full' ); // Full resolution (original size uploaded)\n\nthe_post_thumbnail( array(100, 100) );\n</code></pre>\n\n<p>This might help you.</p>\n"
},
{
"answer_id": 315447,
"author": "jave.web",
"author_id": 45050,
"author_profile": "https://wordpress.stackexchange.com/users/45050",
"pm_score": 3,
"selected": false,
"text": "<p>After you get it's ID ( <a href=\"https://developer.wordpress.org/reference/functions/get_post_thumbnail_id/\" rel=\"noreferrer\"><strong>get_post_thumbnail_id($YOUR_POST_ID)</strong></a> ) you need to know the uploads base url and the attachment meta data.</p>\n\n<p><strong>Uploads base url</strong> can be found in an array returned by <a href=\"https://developer.wordpress.org/reference/functions/wp_upload_dir/\" rel=\"noreferrer\"><strong>wp_upload_dir()</strong></a>.</p>\n\n<p><strong>Attachment meta data</strong> can be retrieved by <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_metadata/\" rel=\"noreferrer\"><strong>wp_get_attachment_metadata()</strong></a>.</p>\n\n<p>Here is a handy function I wrote that prepares the url data for <strong>any image attachment, not just featured</strong>.</p>\n\n<pre><code>function prepareImageData( $attachment_id ){\n $uploads_baseurl = wp_upload_dir()['baseurl'];\n\n $prepared = [];\n $data = wp_get_attachment_metadata($attachment_id);\n $prepared = [\n 'mime_type' => get_post_mime_type($attachment_id),\n 'url' => $uploads_baseurl.'/'.$data['file'],\n 'sizes' => [],\n ];\n\n foreach( $data['sizes'] as $size => $sizeInfo ){\n $prepared['sizes'][$size] = [\n 'url' => $uploads_baseurl.'/'.$sizeInfo['file'],\n ];\n }\n\n return $prepared;\n}\n</code></pre>\n"
}
] |
2015/10/25
|
[
"https://wordpress.stackexchange.com/questions/206509",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82471/"
] |
Is there a standard way to get all the registered sizes of the featured images?
One can register different sizes with `add_image_size()`.
What I need, is to get all the sizes of a featured image of a post.
Something like this:
$sizes = get\_post\_feature\_image\_sizes($postid);
...which will return an array of objects like this (here in JSON format):
```
[
{width: 200, height: 300, url: 'http://.........../wp-content/uploads/2015/10/file-200x300.jpg'},
{width: 300, height: 400, url: 'http://.........../wp-content/uploads/2015/10/file.jpg'},
]
```
Is there anything like this, or I will have to scan all the upload folder file names with regex?
|
I don't remember a function that will do precisely that, but it is easily achieved with API overall:
1. Retrieve attachment ID with [`get_post_thumbnail_id()`](https://developer.wordpress.org/reference/functions/get_post_thumbnail_id/)
2. Retrieve available sizes with [`get_intermediate_image_sizes()`](https://developer.wordpress.org/reference/functions/get_intermediate_image_sizes/)
3. For each size use [`wp_get_attachment_image_src()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/), which gives precisely data you need (URL and dimensions).
|
206,516 |
<p>I'm not strong in WP programming, bu I try to understand what to do to enable SVG in my site. I found that in need to add function below to <code>functions.php</code>:</p>
<pre><code>/**
* Add SVG capabilities
*/
function wpcontent_svg_mime_type( $mimes = array() ) {
$mimes['svg'] = 'image/svg+xml';
$mimes['svgz'] = 'image/svg+xml';
return $mimes;
}
add_filter( 'upload_mimes', 'wpcontent_svg_mime_type' );
</code></pre>
<p><code>wpcontent</code> should be replaced with namespace. But how to know what is my WP namespace?</p>
<p>Add lines below to <code>.htaccess</code> file after the line, <code>#End WordPress</code>:</p>
<pre><code># Add SVG Mime Types
AddType image/svg+xml svg
AddType image/svg+xml svgz
</code></pre>
<p>Is anything else I shoud do?</p>
<p>UPD. After this procedure iI have following:</p>
<p>Now I can upload files to Media, but no preview. And when I do insert nothing happens - no new picture.</p>
<p>How to solve this?</p>
|
[
{
"answer_id": 206519,
"author": "RaajTram",
"author_id": 82482,
"author_profile": "https://wordpress.stackexchange.com/users/82482",
"pm_score": 0,
"selected": false,
"text": "<p>Adding the following code to my functions.php works great for me. No need to modify the .htaccess file at all.</p>\n\n<pre><code>function cc_mime_types( $mimes ){\n $mimes['svg'] = 'image/svg+xml';\n return $mimes;\n}\n\nadd_filter( 'upload_mimes', 'cc_mime_types' );\n</code></pre>\n\n<p>This allows me to upload and display SVG images without any issues.</p>\n"
},
{
"answer_id": 206521,
"author": "chrisguitarguy",
"author_id": 6035,
"author_profile": "https://wordpress.stackexchange.com/users/6035",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>But how to know what is my WP namespace?</p>\n</blockquote>\n\n<p>namespacing a function, in WP land, just means prefixing it with something that makes it more unique and unlikely to conflict with anything else. Generally that means you do both a \"vendor\" and a \"package\". For instance, if I'm building a plugin, my function upload mimes function might be...</p>\n\n<pre><code>add_filter('upload_mimes', 'chrisguitarguy_pluginname_mimes');\nfunction chrisguitarguy_pluginname_mimes($mimes)\n{\n // ...\n}\n</code></pre>\n\n<p>Where <code>chrisguitarguy</code> is my \"vendor\" name and <code>pluginname</code> is the package. You can do this <a href=\"https://wordpress.stackexchange.com/questions/63668/autoloading-namespaces-in-wordpress-plugins-themes-can-it-work\">PHP namespaces</a> as well.</p>\n\n<pre><code>namespace Chrisguitarguy\\PluginName;\n\nadd_action('upload_mimes', __NAMESPACE__.'\\\\mimes');\nfunction mimes($mimes)\n{\n // ...\n}\n</code></pre>\n\n<blockquote>\n <p>Is anything else I shoud do?</p>\n</blockquote>\n\n<p>Nope, what you have is perfect. You may want to specify that svgz is gzipped in your <code>.htaccess</code>.</p>\n\n<pre><code>AddType image/svg+xml .svg .svgz\n// http://httpd.apache.org/docs/2.2/mod/mod_mime.html#addencoding\nAddEncoding gzip svgz\n</code></pre>\n\n<p>Newer versions of apache might include this config by default?</p>\n"
}
] |
2015/10/25
|
[
"https://wordpress.stackexchange.com/questions/206516",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74608/"
] |
I'm not strong in WP programming, bu I try to understand what to do to enable SVG in my site. I found that in need to add function below to `functions.php`:
```
/**
* Add SVG capabilities
*/
function wpcontent_svg_mime_type( $mimes = array() ) {
$mimes['svg'] = 'image/svg+xml';
$mimes['svgz'] = 'image/svg+xml';
return $mimes;
}
add_filter( 'upload_mimes', 'wpcontent_svg_mime_type' );
```
`wpcontent` should be replaced with namespace. But how to know what is my WP namespace?
Add lines below to `.htaccess` file after the line, `#End WordPress`:
```
# Add SVG Mime Types
AddType image/svg+xml svg
AddType image/svg+xml svgz
```
Is anything else I shoud do?
UPD. After this procedure iI have following:
Now I can upload files to Media, but no preview. And when I do insert nothing happens - no new picture.
How to solve this?
|
>
> But how to know what is my WP namespace?
>
>
>
namespacing a function, in WP land, just means prefixing it with something that makes it more unique and unlikely to conflict with anything else. Generally that means you do both a "vendor" and a "package". For instance, if I'm building a plugin, my function upload mimes function might be...
```
add_filter('upload_mimes', 'chrisguitarguy_pluginname_mimes');
function chrisguitarguy_pluginname_mimes($mimes)
{
// ...
}
```
Where `chrisguitarguy` is my "vendor" name and `pluginname` is the package. You can do this [PHP namespaces](https://wordpress.stackexchange.com/questions/63668/autoloading-namespaces-in-wordpress-plugins-themes-can-it-work) as well.
```
namespace Chrisguitarguy\PluginName;
add_action('upload_mimes', __NAMESPACE__.'\\mimes');
function mimes($mimes)
{
// ...
}
```
>
> Is anything else I shoud do?
>
>
>
Nope, what you have is perfect. You may want to specify that svgz is gzipped in your `.htaccess`.
```
AddType image/svg+xml .svg .svgz
// http://httpd.apache.org/docs/2.2/mod/mod_mime.html#addencoding
AddEncoding gzip svgz
```
Newer versions of apache might include this config by default?
|
206,523 |
<p>I'm trying to remove current_page_parent class from the blog index menu item (I got a custom page to display all blog posts and it is in the menu) when navigating custom post type archive page and custom post type posts.</p>
<p>I've found similar questions but I can't figure out how to solve it. In addition, I don't have the current_page_parent when navigating the custom_post_type (I guess it is related).</p>
|
[
{
"answer_id": 206536,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 5,
"selected": true,
"text": "<p>You can use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/nav_menu_css_class\" rel=\"noreferrer\"><code>nav_menu_css_class</code></a> filter to add or remove classes from menu items. Each individual menu item will have this filter applied. An array of classes and the menu item object will be passed to the function, and you will <code>return</code> an array of the classes you want the menu item to have.</p>\n\n<p>PHP's <a href=\"http://php.net/manual/en/function.array-diff.php\" rel=\"noreferrer\"><code>array_diff</code></a> can be used to remove classes, and adding items can be accomplished by appending class names to the array via <code>$classes[] = 'some-class-name'</code>. You can use the <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"noreferrer\"><code>Conditional Tags</code></a> to check what sort of page is currently being viewed to determine what you need to add or remove.</p>\n\n<p>Here's a quick example that checks if the page currently being viewed is either an archive or single post of the type <code>your-post-type</code>, and the menu item name is <code>Blog</code>. If those conditions are met, the <code>current_page_parent</code> class is removed from the array of classes for that menu item. You can add to or tweak this for your needs.</p>\n\n<pre><code>function wpdev_nav_classes( $classes, $item ) {\n if( ( is_post_type_archive( 'your-post-type' ) || is_singular( 'your-post-type' ) )\n && $item->title == 'Blog' ){\n $classes = array_diff( $classes, array( 'current_page_parent' ) );\n }\n return $classes;\n}\nadd_filter( 'nav_menu_css_class', 'wpdev_nav_classes', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 329379,
"author": "richk",
"author_id": 161686,
"author_profile": "https://wordpress.stackexchange.com/users/161686",
"pm_score": 3,
"selected": false,
"text": "<p>The current answer is great but it assumes the title of blog's navigation item is \"Blog\". This could cause problems if the a user ever modifies the nav item in WordPress. The following code is universal as it compares the page id of the nav item against the page id of the blog stored in WordPress options.</p>\n\n<pre><code>function my_custom_post_type_nav_classes( $classes, $item ) {\n $custom_post_type = 'custom-post-type';\n if( ( is_post_type_archive( $custom_post_type) || is_singular( $custom_post_type ) )\n && get_post_meta( $item->ID, '_menu_item_object_id', true ) == get_option( 'page_for_posts' ) ){\n $classes = array_diff( $classes, array( 'current_page_parent' ) );\n }\n return $classes;\n }\n add_filter( 'nav_menu_css_class', 'my_custom_post_type_nav_classes', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 351526,
"author": "GDY",
"author_id": 52227,
"author_profile": "https://wordpress.stackexchange.com/users/52227",
"pm_score": 2,
"selected": false,
"text": "<p>Ok both answers are not very elegant because you have to enter the CPTs name manually. Here is a simple drop in snippet. It is pretty much copied from <a href=\"https://blog.kulturbanause.de/2017/08/wordpress-css-klasse-current_page_parent-bei-custom-post-types-aus-dem-menue-entfernen/\" rel=\"nofollow noreferrer\">here</a> so kudos to that site.</p>\n<p><strong>This snippet removes the <code>current_page_parent</code> class of the blog menu item:</strong></p>\n<pre><code>add_filter( 'nav_menu_css_class', 'theme_remove_cpt_blog_class', 10, 3 );\n\nfunction theme_remove_cpt_blog_class( $classes, $item, $args ) {\n\n\n if( !is_singular( 'post' ) AND !is_category() AND !is_tag() AND !is_date() ):\n\n $blog_page_id = intval( get_option( 'page_for_posts' ) );\n\n if( $blog_page_id != 0 AND $item->object_id == $blog_page_id )\n unset( $classes[ array_search( 'current_page_parent', $classes ) ] ); \n\n endif;\n\n\n return $classes;\n\n\n}\n</code></pre>\n<p>Altough it wasn't asked primarily i think when removing the class from the blog menu item in most cases you want a class to highlight the CPTs archive menu item so here is a snippet for that too.</p>\n<p><strong>This snippet adds a <code>current_page_parent</code> class on the archive menu item of a CPT:</strong></p>\n<pre><code>add_action( 'nav_menu_css_class', 'theme_add_cpt_ancestor_class', 10, 3 );\n\nfunction theme_add_cpt_ancestor_class( $classes, $item, $args ) {\n\n\n global $post;\n\n $current_post_type = get_post_type_object( get_post_type( $post->ID ) );\n\n if ( $current_post_type === 'post' ) {\n return $classes;\n }\n\n $current_post_type_slug = is_array( $current_post_type->rewrite ) ? $current_post_type->rewrite['slug'] : $current_post_type->name;\n\n $menu_slug = strtolower( trim( $item->url ) );\n\n if( strpos( $menu_slug, $current_post_type_slug ) !== false )\n $classes[] = 'current_page_parent';\n\n \n return $classes;\n\n\n}\n</code></pre>\n"
},
{
"answer_id": 363003,
"author": "blogob",
"author_id": 159378,
"author_profile": "https://wordpress.stackexchange.com/users/159378",
"pm_score": 0,
"selected": false,
"text": "<p>I build custom template page instead of using custom post type archive default pages.\nAnd I faced that issue too. When I was on that custom template pages, or in the CPT single pages, I had the Blog menu item that was highlithed, as if there were all children of the Blog page.</p>\n\n<p>I finaly used the functions mentioned by GDY and it works great. Thank you !</p>\n\n<p>But I still don't understand why suddenly and what in the code make the blog menu item to highlight when on a custom page or CPT.</p>\n\n<p>Does someone have the answer ?</p>\n"
}
] |
2015/10/25
|
[
"https://wordpress.stackexchange.com/questions/206523",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60103/"
] |
I'm trying to remove current\_page\_parent class from the blog index menu item (I got a custom page to display all blog posts and it is in the menu) when navigating custom post type archive page and custom post type posts.
I've found similar questions but I can't figure out how to solve it. In addition, I don't have the current\_page\_parent when navigating the custom\_post\_type (I guess it is related).
|
You can use the [`nav_menu_css_class`](https://codex.wordpress.org/Plugin_API/Filter_Reference/nav_menu_css_class) filter to add or remove classes from menu items. Each individual menu item will have this filter applied. An array of classes and the menu item object will be passed to the function, and you will `return` an array of the classes you want the menu item to have.
PHP's [`array_diff`](http://php.net/manual/en/function.array-diff.php) can be used to remove classes, and adding items can be accomplished by appending class names to the array via `$classes[] = 'some-class-name'`. You can use the [`Conditional Tags`](https://codex.wordpress.org/Conditional_Tags) to check what sort of page is currently being viewed to determine what you need to add or remove.
Here's a quick example that checks if the page currently being viewed is either an archive or single post of the type `your-post-type`, and the menu item name is `Blog`. If those conditions are met, the `current_page_parent` class is removed from the array of classes for that menu item. You can add to or tweak this for your needs.
```
function wpdev_nav_classes( $classes, $item ) {
if( ( is_post_type_archive( 'your-post-type' ) || is_singular( 'your-post-type' ) )
&& $item->title == 'Blog' ){
$classes = array_diff( $classes, array( 'current_page_parent' ) );
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'wpdev_nav_classes', 10, 2 );
```
|
206,561 |
<p>I am learning about shortcodes. I've made 2 shortcodes that makes an accordion with bootstrap. One shortode (accordionGroup) creates the body that contains one or more shortcodes to make the items and it's content (accordionItem).</p>
<p>Now I need to create 2 different accordion. The problem is: I need a different id for each accordion and parse it to each item from that accordion. That is to make the accordion animation.</p>
<p>Here is the code</p>
<pre><code>//This is the accordion container
function accordionGroup( $atts, $content = null )
{
extract(shortcode_atts(array(
'id_container' => '',
), $atts));
return "<div class='panel-group' id=".$id_container." role='tablist' aria-multiselectable='true'>".do_shortcode($content)."</div>";
}
add_shortcode( 'accordion-group', 'accordionGroup');
//This is the accordion item. It's need a reference from the accordion ID
function accordionItem( $atts, $content = null)
{
extract(shortcode_atts(array(
'titulo' => '',
'id' => '',
), $atts));
return "
<div class='panel panel-default'>
<div class='panel-heading' role='tab' id=".$id.">
<h4 class='panel-title'>
<a class='collapsed' role='button' data-toggle='collapse' data-parent='#the-reference-goes-here' href='#".$id."-collapse' aria-expanded='false' aria-controls=".$id."-collapse'>".$titulo."</a>
</h4>
</div>
<div id='".$id."-collapse' class='panel-collapse collapse' role='tabpanel' aria-labelledby=".$id.">
<div class='panel-body'>".$content."</div>
</div>
</div>";
}
add_shortcode( 'accordion-item', 'accordionItem');
</code></pre>
|
[
{
"answer_id": 206565,
"author": "Balas",
"author_id": 17849,
"author_profile": "https://wordpress.stackexchange.com/users/17849",
"pm_score": 0,
"selected": false,
"text": "<p>I have just read your code and is this correct </p>\n\n<pre><code>$id_container \n</code></pre>\n\n<p>instead </p>\n\n<pre><code>$atts['id_container']\n</code></pre>\n\n<p>And may be this code error for you. Can you check once this?</p>\n"
},
{
"answer_id": 206599,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 1,
"selected": false,
"text": "<p>You could pass the variable via a <code>global</code> but it would be neater to trap it in a static variable:</p>\n\n<pre><code>function track_acc_id($new_id = false) {\n static $id;\n if (!empty($new_id)) {\n $id = $new_id;\n }\n return $id;\n}\n\n//This is the accordion container\nfunction accordionGroup( $atts, $content = null )\n{\n extract(shortcode_atts(array(\n 'id_container' => '',\n), $atts));\n\n track_acc_id($id_container);\n\n return \"<div class='panel-group' id=\".$id_container.\" role='tablist' aria-multiselectable='true'>\".do_shortcode($content).\"</div>\";\n}\nadd_shortcode( 'accordion-group', 'accordionGroup');\n\n//This is the accordion item. It's need a reference from the accordion ID\nfunction accordionItem( $atts, $content = null)\n{\n extract(shortcode_atts(array(\n 'titulo' => '',\n 'id' => '',\n), $atts));\n\n $id = track_acc_id();\n\n return \"\n <div class='panel panel-default'>\n <div class='panel-heading' role='tab' id=\".$id.\">\n <h4 class='panel-title'>\n <a class='collapsed' role='button' data-toggle='collapse' data-parent='#the-reference-goes-here' href='#\".$id.\"-collapse' aria-expanded='false' aria-controls=\".$id.\"-collapse'>\".$titulo.\"</a>\n </h4>\n </div>\n <div id='\".$id.\"-collapse' class='panel-collapse collapse' role='tabpanel' aria-labelledby=\".$id.\">\n <div class='panel-body'>\".$content.\"</div>\n </div>\n </div>\";\n}\nadd_shortcode( 'accordion-item', 'accordionItem');\n\necho do_shortcode('[accordion-group id_container=\"d00d\"]');\necho do_shortcode('[accordion-item]');\n</code></pre>\n\n<p>Or the whole thing into a class.</p>\n"
}
] |
2015/10/26
|
[
"https://wordpress.stackexchange.com/questions/206561",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82502/"
] |
I am learning about shortcodes. I've made 2 shortcodes that makes an accordion with bootstrap. One shortode (accordionGroup) creates the body that contains one or more shortcodes to make the items and it's content (accordionItem).
Now I need to create 2 different accordion. The problem is: I need a different id for each accordion and parse it to each item from that accordion. That is to make the accordion animation.
Here is the code
```
//This is the accordion container
function accordionGroup( $atts, $content = null )
{
extract(shortcode_atts(array(
'id_container' => '',
), $atts));
return "<div class='panel-group' id=".$id_container." role='tablist' aria-multiselectable='true'>".do_shortcode($content)."</div>";
}
add_shortcode( 'accordion-group', 'accordionGroup');
//This is the accordion item. It's need a reference from the accordion ID
function accordionItem( $atts, $content = null)
{
extract(shortcode_atts(array(
'titulo' => '',
'id' => '',
), $atts));
return "
<div class='panel panel-default'>
<div class='panel-heading' role='tab' id=".$id.">
<h4 class='panel-title'>
<a class='collapsed' role='button' data-toggle='collapse' data-parent='#the-reference-goes-here' href='#".$id."-collapse' aria-expanded='false' aria-controls=".$id."-collapse'>".$titulo."</a>
</h4>
</div>
<div id='".$id."-collapse' class='panel-collapse collapse' role='tabpanel' aria-labelledby=".$id.">
<div class='panel-body'>".$content."</div>
</div>
</div>";
}
add_shortcode( 'accordion-item', 'accordionItem');
```
|
You could pass the variable via a `global` but it would be neater to trap it in a static variable:
```
function track_acc_id($new_id = false) {
static $id;
if (!empty($new_id)) {
$id = $new_id;
}
return $id;
}
//This is the accordion container
function accordionGroup( $atts, $content = null )
{
extract(shortcode_atts(array(
'id_container' => '',
), $atts));
track_acc_id($id_container);
return "<div class='panel-group' id=".$id_container." role='tablist' aria-multiselectable='true'>".do_shortcode($content)."</div>";
}
add_shortcode( 'accordion-group', 'accordionGroup');
//This is the accordion item. It's need a reference from the accordion ID
function accordionItem( $atts, $content = null)
{
extract(shortcode_atts(array(
'titulo' => '',
'id' => '',
), $atts));
$id = track_acc_id();
return "
<div class='panel panel-default'>
<div class='panel-heading' role='tab' id=".$id.">
<h4 class='panel-title'>
<a class='collapsed' role='button' data-toggle='collapse' data-parent='#the-reference-goes-here' href='#".$id."-collapse' aria-expanded='false' aria-controls=".$id."-collapse'>".$titulo."</a>
</h4>
</div>
<div id='".$id."-collapse' class='panel-collapse collapse' role='tabpanel' aria-labelledby=".$id.">
<div class='panel-body'>".$content."</div>
</div>
</div>";
}
add_shortcode( 'accordion-item', 'accordionItem');
echo do_shortcode('[accordion-group id_container="d00d"]');
echo do_shortcode('[accordion-item]');
```
Or the whole thing into a class.
|
206,585 |
<p>I am trying to make my theme translatable so I am using the following command to output text. But its just returning an empty value some reason? No error is displayed</p>
<pre><code><?php __('PLAYER POINTS AT A GLANCE.','gogreensoccer');?>
<div class="skill-title">
<h3><?php __('PLAYER POINTS AT A GLANCE.','gogreensoccer');?></h3>
</div>
<div class="col-md-5 col-sm-12">
<div class="kids-dashboard-skill">
<div class="skill-show">
<div class="points"><h3><span><?php echo $player->display( 'points' ); ?></span>POINTS</h3></div>
<div class="circle-skill"><div id="circle" data-size="<?php echo $player->display( 'points' ); ?>" data-thickness="35"></div></div>
</div>
<div class="skill-button">
<center>
<button><?php __('VIEW MY TEAM MATES.','gogreensoccer');?></button>
<button><?php __('Player ID','gogreensoccer');?><?php echo $playerId;?></button>
</center>
</div>
</div>
</code></pre>
<p>But I'm not getting any text outputed obv I want a default value here if no translation exists I though <code>__(string,themename)</code> would achieve this.</p>
|
[
{
"answer_id": 206589,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": true,
"text": "<p>The localizing functions have two variaties, one that echos the string value and the other one that returns it's string value.</p>\n\n<p>Because you would want to display the string (<em><code>echo</code> it</em>), you would want the correct function for the specific string which will echo the output. For easy simple strings (<em><code>__('PLAYER POINTS AT A GLANCE.','gogreensoccer')</code></em>) like you have above, the <code>__()</code> and <code>_e()</code> functions would work</p>\n\n<ul>\n<li><p><code>__('PLAYER POINTS AT A GLANCE.','gogreensoccer')</code> would return the string value, useful if you need add a value to a variable and store for later use</p></li>\n<li><p><code>_e('PLAYER POINTS AT A GLANCE.','gogreensoccer')</code> would be what you need. This will echo the string to screen</p></li>\n</ul>\n\n<p>Both are valid in all plugins and themes</p>\n"
},
{
"answer_id": 206590,
"author": "Ajay Khandal",
"author_id": 82505,
"author_profile": "https://wordpress.stackexchange.com/users/82505",
"pm_score": 0,
"selected": false,
"text": "<p>Use your theme name.</p>\n\n<p>if your theme name is \"gogreensoccer\" then this code is fine else use your theme name at the place of \"gogreensoccer\" then this will work.After that generate wpml theme translation option to generate your theme strings.</p>\n"
}
] |
2015/10/26
|
[
"https://wordpress.stackexchange.com/questions/206585",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3582/"
] |
I am trying to make my theme translatable so I am using the following command to output text. But its just returning an empty value some reason? No error is displayed
```
<?php __('PLAYER POINTS AT A GLANCE.','gogreensoccer');?>
<div class="skill-title">
<h3><?php __('PLAYER POINTS AT A GLANCE.','gogreensoccer');?></h3>
</div>
<div class="col-md-5 col-sm-12">
<div class="kids-dashboard-skill">
<div class="skill-show">
<div class="points"><h3><span><?php echo $player->display( 'points' ); ?></span>POINTS</h3></div>
<div class="circle-skill"><div id="circle" data-size="<?php echo $player->display( 'points' ); ?>" data-thickness="35"></div></div>
</div>
<div class="skill-button">
<center>
<button><?php __('VIEW MY TEAM MATES.','gogreensoccer');?></button>
<button><?php __('Player ID','gogreensoccer');?><?php echo $playerId;?></button>
</center>
</div>
</div>
```
But I'm not getting any text outputed obv I want a default value here if no translation exists I though `__(string,themename)` would achieve this.
|
The localizing functions have two variaties, one that echos the string value and the other one that returns it's string value.
Because you would want to display the string (*`echo` it*), you would want the correct function for the specific string which will echo the output. For easy simple strings (*`__('PLAYER POINTS AT A GLANCE.','gogreensoccer')`*) like you have above, the `__()` and `_e()` functions would work
* `__('PLAYER POINTS AT A GLANCE.','gogreensoccer')` would return the string value, useful if you need add a value to a variable and store for later use
* `_e('PLAYER POINTS AT A GLANCE.','gogreensoccer')` would be what you need. This will echo the string to screen
Both are valid in all plugins and themes
|
206,611 |
<p>I know that I can display 4 random posts by doing something like:</p>
<pre><code>get_posts('orderby=rand&numberposts=4');
</code></pre>
<p> </p>
<p>What I'm trying to achieve is starting with a random item, but then showing the next 3 posts that are in chronological order.</p>
<p>I'm thinking something along the lines of this:</p>
<pre><code>$posts = get_posts('orderby=rand&numberposts=1');
foreach($posts as $post) {
the_title();
//get next 3 chronological posts and loop
}
</code></pre>
<p>I guess I need to use something like the 'offset' parameter, but with a post id instead of a position?</p>
|
[
{
"answer_id": 206589,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": true,
"text": "<p>The localizing functions have two variaties, one that echos the string value and the other one that returns it's string value.</p>\n\n<p>Because you would want to display the string (<em><code>echo</code> it</em>), you would want the correct function for the specific string which will echo the output. For easy simple strings (<em><code>__('PLAYER POINTS AT A GLANCE.','gogreensoccer')</code></em>) like you have above, the <code>__()</code> and <code>_e()</code> functions would work</p>\n\n<ul>\n<li><p><code>__('PLAYER POINTS AT A GLANCE.','gogreensoccer')</code> would return the string value, useful if you need add a value to a variable and store for later use</p></li>\n<li><p><code>_e('PLAYER POINTS AT A GLANCE.','gogreensoccer')</code> would be what you need. This will echo the string to screen</p></li>\n</ul>\n\n<p>Both are valid in all plugins and themes</p>\n"
},
{
"answer_id": 206590,
"author": "Ajay Khandal",
"author_id": 82505,
"author_profile": "https://wordpress.stackexchange.com/users/82505",
"pm_score": 0,
"selected": false,
"text": "<p>Use your theme name.</p>\n\n<p>if your theme name is \"gogreensoccer\" then this code is fine else use your theme name at the place of \"gogreensoccer\" then this will work.After that generate wpml theme translation option to generate your theme strings.</p>\n"
}
] |
2015/10/26
|
[
"https://wordpress.stackexchange.com/questions/206611",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58105/"
] |
I know that I can display 4 random posts by doing something like:
```
get_posts('orderby=rand&numberposts=4');
```
What I'm trying to achieve is starting with a random item, but then showing the next 3 posts that are in chronological order.
I'm thinking something along the lines of this:
```
$posts = get_posts('orderby=rand&numberposts=1');
foreach($posts as $post) {
the_title();
//get next 3 chronological posts and loop
}
```
I guess I need to use something like the 'offset' parameter, but with a post id instead of a position?
|
The localizing functions have two variaties, one that echos the string value and the other one that returns it's string value.
Because you would want to display the string (*`echo` it*), you would want the correct function for the specific string which will echo the output. For easy simple strings (*`__('PLAYER POINTS AT A GLANCE.','gogreensoccer')`*) like you have above, the `__()` and `_e()` functions would work
* `__('PLAYER POINTS AT A GLANCE.','gogreensoccer')` would return the string value, useful if you need add a value to a variable and store for later use
* `_e('PLAYER POINTS AT A GLANCE.','gogreensoccer')` would be what you need. This will echo the string to screen
Both are valid in all plugins and themes
|
206,671 |
<p>The functions <a href="https://codex.wordpress.org/Function_Reference/get_bloginfo" rel="nofollow">get_bloginfo</a>() and bloginfo() both return information about the blog but accessing it each time seems unnecessary. Is there a function that will return the bloginfo as an object with properties? </p>
<p><strong>More Info:</strong><br>
I have tokens in my markup and I want to replace those tokens with the blog info. Since I'm replacing tokens over multiple posts I don't want to call <code>get_bloginfo("name");</code> multiple times. Instead I want to put it into an object I can reuse for each call. </p>
|
[
{
"answer_id": 206679,
"author": "1.21 gigawatts",
"author_id": 29247,
"author_profile": "https://wordpress.stackexchange.com/users/29247",
"pm_score": 1,
"selected": true,
"text": "<p>Here is my workaround if one does not exist: </p>\n\n<pre><code>/**\n * Get an object with blog info values\n */\nfunction getBlogInfo() {\n $info = new stdClass();\n\n $info->name = get_bloginfo(\"name\");\n $info->description = get_bloginfo(\"description\");\n $info->wpurl = get_bloginfo(\"wpurl\");\n $info->url = get_bloginfo(\"url\");\n $info->admin_email = get_bloginfo(\"admin_email\");\n $info->charset = get_bloginfo(\"charset\");\n $info->version = get_bloginfo(\"version\");\n $info->html_type = get_bloginfo(\"html_type\");\n $info->text_direction = get_bloginfo(\"text_direction\");\n $info->language = get_bloginfo(\"language\");\n $info->stylesheet_url = get_bloginfo(\"stylesheet_url\");\n $info->stylesheet_directory = get_bloginfo(\"stylesheet_directory\");\n $info->template_url = get_bloginfo(\"template_url\");\n $info->template_directory = get_bloginfo(\"template_url\");\n $info->pingback_url = get_bloginfo(\"pingback_url\");\n $info->atom_url = get_bloginfo(\"atom_url\");\n $info->rdf_url = get_bloginfo(\"rdf_url\");\n $info->rss_url = get_bloginfo(\"rss_url\");\n $info->rss2_url = get_bloginfo(\"rss2_url\");\n $info->comments_atom_url = get_bloginfo(\"comments_atom_url\");\n $info->comments_rss2_url = get_bloginfo(\"comments_rss2_url\");\n $info->siteurl = home_url();\n $info->home = home_url();\n\n return $info;\n}\n\n// the following is pseudo code to give you example of what I'm doing\n$info = getBlogInfo();\n\nfor ($i=0;i<count(posts);$i++) {\n $post = $posts[i];\n $value = $post->value.replace(\"{name}\", $info->name);\n $value = $post->value.replace(\"{description}\", $info->description);\n $postsArray.push($post);\n}\n</code></pre>\n\n<p>The reason I chose this as an answer is because I need to access the properties of the object more than once. So once it's created subsequent calls are getting the values not calling the functions repeatedly which may or may not be expensive. I don't know. </p>\n\n<p>Also, the question and answer is not asking \"the best\" way you can do things it's asking how to do a specific thing and this answer fits that specific thing mentioned in the question. I'm saying all this because people down vote all the time for not doing things the way they were taught or \"the best\" way. </p>\n\n<p><em>Update: I added a use case so you can see how I'm using the function and method. I don't always do this but I think it will explain things.</em> </p>\n"
},
{
"answer_id": 206746,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>Taken from the source code of <a href=\"https://developer.wordpress.org/reference/functions/get_bloginfo/\" rel=\"nofollow\"><code>get_bloginfo()</code></a>, Here is a very very simple class you can utelize and extent at your will. </p>\n\n<p>I have decided to make use of methods, making properties public from a class is really not great coding and not recommended. I know Wordpress thrive on public properties, but that is Wordpress.</p>\n\n<p>Here is the class (<em>which you should convert to make use of proper namespacing, as I said, this is an extremely simple and plain class</em>)</p>\n\n<pre><code>class GetBlogInfo\n{\n // Return the home URL\n public function homeURL() \n {\n return home_url();\n }\n\n // Return the site URL\n public function siteURL() \n {\n return site_url();\n }\n\n // Return the blog description\n public function description() \n {\n return get_option('blogdescription');\n }\n\n // Get the feed links\n public function getFeedLink( $link = '' ) \n {\n switch( $link ) {\n case 'rdf_url':\n $output = 'rdf';\n break;\n case 'rss_url':\n $output = 'rss';\n break;\n case 'rss2_url':\n $output = 'rss2';\n break;\n case 'atom_url':\n $output = 'atom';\n break;\n case 'comments_atom_url':\n $output = 'comments_atom';\n break;\n case 'comments_rss2_url':\n $output = 'comments_rss2';\n break;\n default:\n $output = false;\n break;\n }\n\n if ( $output ) {\n return get_feed_link( $output );\n } else {\n return false;\n }\n }\n\n // Return the blog options. Default is name\n public function getOptions( $option = 'name' ) \n {\n switch( $option ) {\n case 'admin_email':\n $output = 'admin_email';\n break;\n case 'charset':\n $output = 'blog_charset';\n break;\n case 'html_type':\n $output = 'html_type';\n break;\n case 'name':\n default:\n $output = 'blogname';\n break;\n }\n\n return get_option( $output );\n }\n\n // Return the blog language setting\n public function language() \n {\n return str_replace( '_', '-', get_locale() );\n }\n\n // Return the Wordpress version\n public function version() \n {\n global $wp_version;\n return $wp_version;\n }\n\n // Return the pingback URL\n public function pingbackURL() \n {\n return site_url( 'xmlrpc.php' );\n }\n\n // Return the path to main stylesheet\n public function stylesheetURL() \n {\n return get_stylesheet_uri();\n }\n\n // Return the stylesheet directory uri\n public function stylesheetDirectory() \n {\n return get_stylesheet_directory_uri();\n }\n\n // Return the template directory uri\n public function templateDirectory() \n {\n return get_template_directory_uri();\n }\n}\n</code></pre>\n\n<p>You can use the class as follow:</p>\n\n<pre><code>$q = new GetBlogInfo();\necho $q->homeURL() . '</br>';\necho $q->siteURL() . '</br>';\necho $q->description() . '</br>';\necho $q->getFeedLink( 'rdf_url' ) . '</br>';\necho $q->getFeedLink( 'rss_url' ) . '</br>';\necho $q->getFeedLink( 'rss2_url' ) . '</br>';\necho $q->getFeedLink( 'atom_url' ) . '</br>';\necho $q->getFeedLink( 'comments_atom_url' ) . '</br>';\necho $q->getFeedLink( 'comments_rss2_url' ) . '</br>';\necho $q->getOptions( 'name' ) . '</br>';\necho $q->getOptions( 'admin_email' ) . '</br>';\necho $q->getOptions( 'charset' ) . '</br>';\necho $q->getOptions( 'html_type' ) . '</br>';\necho $q->language() . '</br>';\necho $q->version() . '</br>';\necho $q->pingbackURL() . '</br>';\necho $q->stylesheetURL() . '</br>';\necho $q->stylesheetDirectory() . '</br>';\necho $q->templateDirectory() . '</br>';\n</code></pre>\n\n<p>This output the following as tested on my test install</p>\n\n<pre><code>http://localhost/wordpress\nhttp://localhost/wordpress\nTrots Afrikaans - Praat Afrikaans of hou jou bek!!!\nhttp://localhost/wordpress/feed/rdf/\nhttp://localhost/wordpress/feed/rss/\nhttp://localhost/wordpress/feed/\nhttp://localhost/wordpress/feed/atom/\nhttp://localhost/wordpress/comments/feed/atom/\nhttp://localhost/wordpress/comments/feed/\nPieter Goosen\[email protected]\nUTF-8\ntext/html\naf-AF\n4.3.1\nhttp://localhost/wordpress/xmlrpc.php\nhttp://localhost/wordpress/wp-content/themes/pietergoosen2014/style.css\nhttp://localhost/wordpress/wp-content/themes/pietergoosen2014\nhttp://localhost/wordpress/wp-content/themes/pietergoosen2014\n</code></pre>\n"
},
{
"answer_id": 212967,
"author": "Otto",
"author_id": 2232,
"author_profile": "https://wordpress.stackexchange.com/users/2232",
"pm_score": 1,
"selected": false,
"text": "<p>These answers are all slower than just using get_bloginfo normally.</p>\n\n<p>Most of the various things that the get_bloginfo function can get use the built in WordPress memory caching system. They don't generally suffer from speed issues from being called multiple times, because things like options and other stuff that come from the database are cached the first time the data is retrieved. </p>\n\n<p>However, calling it a whole bunch of times for some kind of \"setup\" step like this in advance does make it do a bunch of unnecessary work in querying all that data to start out with, especially if most of that is data you don't actually need to have.</p>\n"
}
] |
2015/10/27
|
[
"https://wordpress.stackexchange.com/questions/206671",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29247/"
] |
The functions [get\_bloginfo](https://codex.wordpress.org/Function_Reference/get_bloginfo)() and bloginfo() both return information about the blog but accessing it each time seems unnecessary. Is there a function that will return the bloginfo as an object with properties?
**More Info:**
I have tokens in my markup and I want to replace those tokens with the blog info. Since I'm replacing tokens over multiple posts I don't want to call `get_bloginfo("name");` multiple times. Instead I want to put it into an object I can reuse for each call.
|
Here is my workaround if one does not exist:
```
/**
* Get an object with blog info values
*/
function getBlogInfo() {
$info = new stdClass();
$info->name = get_bloginfo("name");
$info->description = get_bloginfo("description");
$info->wpurl = get_bloginfo("wpurl");
$info->url = get_bloginfo("url");
$info->admin_email = get_bloginfo("admin_email");
$info->charset = get_bloginfo("charset");
$info->version = get_bloginfo("version");
$info->html_type = get_bloginfo("html_type");
$info->text_direction = get_bloginfo("text_direction");
$info->language = get_bloginfo("language");
$info->stylesheet_url = get_bloginfo("stylesheet_url");
$info->stylesheet_directory = get_bloginfo("stylesheet_directory");
$info->template_url = get_bloginfo("template_url");
$info->template_directory = get_bloginfo("template_url");
$info->pingback_url = get_bloginfo("pingback_url");
$info->atom_url = get_bloginfo("atom_url");
$info->rdf_url = get_bloginfo("rdf_url");
$info->rss_url = get_bloginfo("rss_url");
$info->rss2_url = get_bloginfo("rss2_url");
$info->comments_atom_url = get_bloginfo("comments_atom_url");
$info->comments_rss2_url = get_bloginfo("comments_rss2_url");
$info->siteurl = home_url();
$info->home = home_url();
return $info;
}
// the following is pseudo code to give you example of what I'm doing
$info = getBlogInfo();
for ($i=0;i<count(posts);$i++) {
$post = $posts[i];
$value = $post->value.replace("{name}", $info->name);
$value = $post->value.replace("{description}", $info->description);
$postsArray.push($post);
}
```
The reason I chose this as an answer is because I need to access the properties of the object more than once. So once it's created subsequent calls are getting the values not calling the functions repeatedly which may or may not be expensive. I don't know.
Also, the question and answer is not asking "the best" way you can do things it's asking how to do a specific thing and this answer fits that specific thing mentioned in the question. I'm saying all this because people down vote all the time for not doing things the way they were taught or "the best" way.
*Update: I added a use case so you can see how I'm using the function and method. I don't always do this but I think it will explain things.*
|
206,672 |
<p>The site I am working on is skinnnybantonmusic.com
The Lastest News page is suppost to show the blog posts but for some reason none are showing up. (<a href="http://www.skinnybantonmusic.com/latest-news/" rel="nofollow">http://www.skinnybantonmusic.com/latest-news/</a>)</p>
<pre><code><?php get_header(); ?>
<div id="main">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
<?php if ( has_post_thumbnail() ) : ?>
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(); ?>
</a>
<?php endif; ?>
</div>
<?php endwhile; ?>
<?php include (TEMPLATEPATH . '/inc/nav.php' ); ?>
<?php else : ?>
<h2>Not Found</h2>
<?php endif; ?>
</div><!--Main End-->
<?php get_footer(); ?>
</code></pre>
|
[
{
"answer_id": 206679,
"author": "1.21 gigawatts",
"author_id": 29247,
"author_profile": "https://wordpress.stackexchange.com/users/29247",
"pm_score": 1,
"selected": true,
"text": "<p>Here is my workaround if one does not exist: </p>\n\n<pre><code>/**\n * Get an object with blog info values\n */\nfunction getBlogInfo() {\n $info = new stdClass();\n\n $info->name = get_bloginfo(\"name\");\n $info->description = get_bloginfo(\"description\");\n $info->wpurl = get_bloginfo(\"wpurl\");\n $info->url = get_bloginfo(\"url\");\n $info->admin_email = get_bloginfo(\"admin_email\");\n $info->charset = get_bloginfo(\"charset\");\n $info->version = get_bloginfo(\"version\");\n $info->html_type = get_bloginfo(\"html_type\");\n $info->text_direction = get_bloginfo(\"text_direction\");\n $info->language = get_bloginfo(\"language\");\n $info->stylesheet_url = get_bloginfo(\"stylesheet_url\");\n $info->stylesheet_directory = get_bloginfo(\"stylesheet_directory\");\n $info->template_url = get_bloginfo(\"template_url\");\n $info->template_directory = get_bloginfo(\"template_url\");\n $info->pingback_url = get_bloginfo(\"pingback_url\");\n $info->atom_url = get_bloginfo(\"atom_url\");\n $info->rdf_url = get_bloginfo(\"rdf_url\");\n $info->rss_url = get_bloginfo(\"rss_url\");\n $info->rss2_url = get_bloginfo(\"rss2_url\");\n $info->comments_atom_url = get_bloginfo(\"comments_atom_url\");\n $info->comments_rss2_url = get_bloginfo(\"comments_rss2_url\");\n $info->siteurl = home_url();\n $info->home = home_url();\n\n return $info;\n}\n\n// the following is pseudo code to give you example of what I'm doing\n$info = getBlogInfo();\n\nfor ($i=0;i<count(posts);$i++) {\n $post = $posts[i];\n $value = $post->value.replace(\"{name}\", $info->name);\n $value = $post->value.replace(\"{description}\", $info->description);\n $postsArray.push($post);\n}\n</code></pre>\n\n<p>The reason I chose this as an answer is because I need to access the properties of the object more than once. So once it's created subsequent calls are getting the values not calling the functions repeatedly which may or may not be expensive. I don't know. </p>\n\n<p>Also, the question and answer is not asking \"the best\" way you can do things it's asking how to do a specific thing and this answer fits that specific thing mentioned in the question. I'm saying all this because people down vote all the time for not doing things the way they were taught or \"the best\" way. </p>\n\n<p><em>Update: I added a use case so you can see how I'm using the function and method. I don't always do this but I think it will explain things.</em> </p>\n"
},
{
"answer_id": 206746,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>Taken from the source code of <a href=\"https://developer.wordpress.org/reference/functions/get_bloginfo/\" rel=\"nofollow\"><code>get_bloginfo()</code></a>, Here is a very very simple class you can utelize and extent at your will. </p>\n\n<p>I have decided to make use of methods, making properties public from a class is really not great coding and not recommended. I know Wordpress thrive on public properties, but that is Wordpress.</p>\n\n<p>Here is the class (<em>which you should convert to make use of proper namespacing, as I said, this is an extremely simple and plain class</em>)</p>\n\n<pre><code>class GetBlogInfo\n{\n // Return the home URL\n public function homeURL() \n {\n return home_url();\n }\n\n // Return the site URL\n public function siteURL() \n {\n return site_url();\n }\n\n // Return the blog description\n public function description() \n {\n return get_option('blogdescription');\n }\n\n // Get the feed links\n public function getFeedLink( $link = '' ) \n {\n switch( $link ) {\n case 'rdf_url':\n $output = 'rdf';\n break;\n case 'rss_url':\n $output = 'rss';\n break;\n case 'rss2_url':\n $output = 'rss2';\n break;\n case 'atom_url':\n $output = 'atom';\n break;\n case 'comments_atom_url':\n $output = 'comments_atom';\n break;\n case 'comments_rss2_url':\n $output = 'comments_rss2';\n break;\n default:\n $output = false;\n break;\n }\n\n if ( $output ) {\n return get_feed_link( $output );\n } else {\n return false;\n }\n }\n\n // Return the blog options. Default is name\n public function getOptions( $option = 'name' ) \n {\n switch( $option ) {\n case 'admin_email':\n $output = 'admin_email';\n break;\n case 'charset':\n $output = 'blog_charset';\n break;\n case 'html_type':\n $output = 'html_type';\n break;\n case 'name':\n default:\n $output = 'blogname';\n break;\n }\n\n return get_option( $output );\n }\n\n // Return the blog language setting\n public function language() \n {\n return str_replace( '_', '-', get_locale() );\n }\n\n // Return the Wordpress version\n public function version() \n {\n global $wp_version;\n return $wp_version;\n }\n\n // Return the pingback URL\n public function pingbackURL() \n {\n return site_url( 'xmlrpc.php' );\n }\n\n // Return the path to main stylesheet\n public function stylesheetURL() \n {\n return get_stylesheet_uri();\n }\n\n // Return the stylesheet directory uri\n public function stylesheetDirectory() \n {\n return get_stylesheet_directory_uri();\n }\n\n // Return the template directory uri\n public function templateDirectory() \n {\n return get_template_directory_uri();\n }\n}\n</code></pre>\n\n<p>You can use the class as follow:</p>\n\n<pre><code>$q = new GetBlogInfo();\necho $q->homeURL() . '</br>';\necho $q->siteURL() . '</br>';\necho $q->description() . '</br>';\necho $q->getFeedLink( 'rdf_url' ) . '</br>';\necho $q->getFeedLink( 'rss_url' ) . '</br>';\necho $q->getFeedLink( 'rss2_url' ) . '</br>';\necho $q->getFeedLink( 'atom_url' ) . '</br>';\necho $q->getFeedLink( 'comments_atom_url' ) . '</br>';\necho $q->getFeedLink( 'comments_rss2_url' ) . '</br>';\necho $q->getOptions( 'name' ) . '</br>';\necho $q->getOptions( 'admin_email' ) . '</br>';\necho $q->getOptions( 'charset' ) . '</br>';\necho $q->getOptions( 'html_type' ) . '</br>';\necho $q->language() . '</br>';\necho $q->version() . '</br>';\necho $q->pingbackURL() . '</br>';\necho $q->stylesheetURL() . '</br>';\necho $q->stylesheetDirectory() . '</br>';\necho $q->templateDirectory() . '</br>';\n</code></pre>\n\n<p>This output the following as tested on my test install</p>\n\n<pre><code>http://localhost/wordpress\nhttp://localhost/wordpress\nTrots Afrikaans - Praat Afrikaans of hou jou bek!!!\nhttp://localhost/wordpress/feed/rdf/\nhttp://localhost/wordpress/feed/rss/\nhttp://localhost/wordpress/feed/\nhttp://localhost/wordpress/feed/atom/\nhttp://localhost/wordpress/comments/feed/atom/\nhttp://localhost/wordpress/comments/feed/\nPieter Goosen\[email protected]\nUTF-8\ntext/html\naf-AF\n4.3.1\nhttp://localhost/wordpress/xmlrpc.php\nhttp://localhost/wordpress/wp-content/themes/pietergoosen2014/style.css\nhttp://localhost/wordpress/wp-content/themes/pietergoosen2014\nhttp://localhost/wordpress/wp-content/themes/pietergoosen2014\n</code></pre>\n"
},
{
"answer_id": 212967,
"author": "Otto",
"author_id": 2232,
"author_profile": "https://wordpress.stackexchange.com/users/2232",
"pm_score": 1,
"selected": false,
"text": "<p>These answers are all slower than just using get_bloginfo normally.</p>\n\n<p>Most of the various things that the get_bloginfo function can get use the built in WordPress memory caching system. They don't generally suffer from speed issues from being called multiple times, because things like options and other stuff that come from the database are cached the first time the data is retrieved. </p>\n\n<p>However, calling it a whole bunch of times for some kind of \"setup\" step like this in advance does make it do a bunch of unnecessary work in querying all that data to start out with, especially if most of that is data you don't actually need to have.</p>\n"
}
] |
2015/10/27
|
[
"https://wordpress.stackexchange.com/questions/206672",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69541/"
] |
The site I am working on is skinnnybantonmusic.com
The Lastest News page is suppost to show the blog posts but for some reason none are showing up. (<http://www.skinnybantonmusic.com/latest-news/>)
```
<?php get_header(); ?>
<div id="main">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
<?php if ( has_post_thumbnail() ) : ?>
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(); ?>
</a>
<?php endif; ?>
</div>
<?php endwhile; ?>
<?php include (TEMPLATEPATH . '/inc/nav.php' ); ?>
<?php else : ?>
<h2>Not Found</h2>
<?php endif; ?>
</div><!--Main End-->
<?php get_footer(); ?>
```
|
Here is my workaround if one does not exist:
```
/**
* Get an object with blog info values
*/
function getBlogInfo() {
$info = new stdClass();
$info->name = get_bloginfo("name");
$info->description = get_bloginfo("description");
$info->wpurl = get_bloginfo("wpurl");
$info->url = get_bloginfo("url");
$info->admin_email = get_bloginfo("admin_email");
$info->charset = get_bloginfo("charset");
$info->version = get_bloginfo("version");
$info->html_type = get_bloginfo("html_type");
$info->text_direction = get_bloginfo("text_direction");
$info->language = get_bloginfo("language");
$info->stylesheet_url = get_bloginfo("stylesheet_url");
$info->stylesheet_directory = get_bloginfo("stylesheet_directory");
$info->template_url = get_bloginfo("template_url");
$info->template_directory = get_bloginfo("template_url");
$info->pingback_url = get_bloginfo("pingback_url");
$info->atom_url = get_bloginfo("atom_url");
$info->rdf_url = get_bloginfo("rdf_url");
$info->rss_url = get_bloginfo("rss_url");
$info->rss2_url = get_bloginfo("rss2_url");
$info->comments_atom_url = get_bloginfo("comments_atom_url");
$info->comments_rss2_url = get_bloginfo("comments_rss2_url");
$info->siteurl = home_url();
$info->home = home_url();
return $info;
}
// the following is pseudo code to give you example of what I'm doing
$info = getBlogInfo();
for ($i=0;i<count(posts);$i++) {
$post = $posts[i];
$value = $post->value.replace("{name}", $info->name);
$value = $post->value.replace("{description}", $info->description);
$postsArray.push($post);
}
```
The reason I chose this as an answer is because I need to access the properties of the object more than once. So once it's created subsequent calls are getting the values not calling the functions repeatedly which may or may not be expensive. I don't know.
Also, the question and answer is not asking "the best" way you can do things it's asking how to do a specific thing and this answer fits that specific thing mentioned in the question. I'm saying all this because people down vote all the time for not doing things the way they were taught or "the best" way.
*Update: I added a use case so you can see how I'm using the function and method. I don't always do this but I think it will explain things.*
|
206,703 |
<p>I'm a new WordPress developer and recently I've been having problems (on multiple sites) with <code>include_once</code> and <code>require_once</code> for PHP files. If I include <code>(get_theme_directory_uri() . 'subdir/file')</code> the specified file gets included (or required, which leads to fatal errors) but if any WordPress functions are called within 'file' I get something similar to: </p>
<blockquote>
<p>'<strong>Call to undefined function</strong> <code>add_action()</code> in /full/path/to/file'.</p>
</blockquote>
<p>The apparent solution I've found is to do: </p>
<pre><code>include(dirname(__FILE__) . "/subdir/filename");
</code></pre>
<p>Is this right or did I miss 'the WordPress way' to include files somewhere? </p>
|
[
{
"answer_id": 206754,
"author": "thomascharbit",
"author_id": 35003,
"author_profile": "https://wordpress.stackexchange.com/users/35003",
"pm_score": 5,
"selected": false,
"text": "<p>If you check <a href=\"https://codex.wordpress.org/Function_Reference/get_template_directory_uri\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_template_directory_uri</a></p>\n<p>You will see <code>get_template_directory_uri()</code> returns a uri, not a server path.</p>\n<p>You should use instead the <code>get_template_directory()</code> function, which returns the path to the theme, without trailing slash:</p>\n<pre><code>include get_template_directory() . '/subdir/filename.php';\n</code></pre>\n<p>For a plugin you can use the <code>plugin_dir_path()</code> function:</p>\n<pre><code>include plugin_dir_path( __FILE__ ) . '/subdir/filename.php';\n</code></pre>\n"
},
{
"answer_id": 337835,
"author": "Maidul",
"author_id": 21142,
"author_profile": "https://wordpress.stackexchange.com/users/21142",
"pm_score": 4,
"selected": false,
"text": "<p>WordPress 4.7+ introduce get_theme_file_path() functions to include file on WordPress theme.</p>\n\n<p>Include like this:</p>\n\n<pre><code>include get_theme_file_path( '/subdir/filename.php' );\n</code></pre>\n\n<p>The advantage of using this function is on child theme you can override the parent theme file.</p>\n\n<p>Reference : <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_path/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/get_theme_file_path/</a></p>\n"
},
{
"answer_id": 412301,
"author": "Daishi",
"author_id": 45516,
"author_profile": "https://wordpress.stackexchange.com/users/45516",
"pm_score": 0,
"selected": false,
"text": "<p>In the following examples, I assume you are using composer and a child theme might be enabled or not.</p>\n<ol>\n<li>Use this method if you want to include a file within a theme and want to ensure the parent theme's directory is used even if a child theme is enabled:</li>\n</ol>\n<pre class=\"lang-php prettyprint-override\"><code>require get_template_directory() . '/vendor/autoload.php';\n</code></pre>\n<ol start=\"2\">\n<li>Or use this method if you want to include a file within a theme and don't mind whether the parent theme's directory is used or the child theme's directory is used if a child theme is enabled:</li>\n</ol>\n<pre class=\"lang-php prettyprint-override\"><code>require get_stylesheet_directory() . '/vendor/autoload.php';\n</code></pre>\n<ol start=\"3\">\n<li>And lastly, use this method if you want to include a file within a plugin:</li>\n</ol>\n<pre class=\"lang-php prettyprint-override\"><code>require __DIR__ . '/vendor/autoload.php';\n</code></pre>\n<p>Be careful with the last method because the magic constant <code>__DIR__</code> will have a different value depending on the directory in which your php file is located.</p>\n<p>Note that there's no benefit to using the <code>plugin_dir_path()</code> function as it is just a wrapper to the <code>trailingslashit()</code> function.</p>\n<p>The documentation says:</p>\n<blockquote>\n<p>The βpluginβ part of the name is misleading β it can be used for any file, and will not return the directory of a plugin unless you call it within a file in the pluginβs base directory.</p>\n</blockquote>\n<p>See <a href=\"https://developer.wordpress.org/reference/functions/plugin_dir_path/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/plugin_dir_path/</a> for more details.</p>\n<p>Also note that using <code>include</code> is poor practice because a missing file will only raise a warning. Always use <code>require</code> instead, because a missing file will raise a fatal error and won't stay unnoticed.</p>\n"
}
] |
2015/10/27
|
[
"https://wordpress.stackexchange.com/questions/206703",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82567/"
] |
I'm a new WordPress developer and recently I've been having problems (on multiple sites) with `include_once` and `require_once` for PHP files. If I include `(get_theme_directory_uri() . 'subdir/file')` the specified file gets included (or required, which leads to fatal errors) but if any WordPress functions are called within 'file' I get something similar to:
>
> '**Call to undefined function** `add_action()` in /full/path/to/file'.
>
>
>
The apparent solution I've found is to do:
```
include(dirname(__FILE__) . "/subdir/filename");
```
Is this right or did I miss 'the WordPress way' to include files somewhere?
|
If you check <https://codex.wordpress.org/Function_Reference/get_template_directory_uri>
You will see `get_template_directory_uri()` returns a uri, not a server path.
You should use instead the `get_template_directory()` function, which returns the path to the theme, without trailing slash:
```
include get_template_directory() . '/subdir/filename.php';
```
For a plugin you can use the `plugin_dir_path()` function:
```
include plugin_dir_path( __FILE__ ) . '/subdir/filename.php';
```
|
206,712 |
<p>How do I put the homepage link ? Right now it's not correct.</p>
<pre><code> <p><?php _e( 'The page you are looking for is not here. Why donβt you try the <a href="<?php echo esc_url( home_url( '/' ) ); ?>">homepage</a>?', 'braveandco' ); ?></p>
</code></pre>
|
[
{
"answer_id": 206716,
"author": "Aric Watson",
"author_id": 81449,
"author_profile": "https://wordpress.stackexchange.com/users/81449",
"pm_score": 1,
"selected": false,
"text": "<p>Looks like bad syntax - try:</p>\n\n<pre><code> <p><?php _e( 'The page you are looking for is not here. Why donβt you try the <a href=\"' . esc_url( home_url( '/' ) ) . '\">homepage</a>?', 'braveandco' ); ?></p>\n</code></pre>\n"
},
{
"answer_id": 206717,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 3,
"selected": false,
"text": "<p>You are using PHP inside a single quote and a malformed one at that. That won't work. Step one is to get that string right:</p>\n\n<pre><code>_e( 'The page you are looking for is not here. Why donβt you try the <a href=\"'.esc_url( home_url( '/' ) ).'\">homepage</a>?', 'braveandco' );\n</code></pre>\n\n<p>That is pure PHP. Check PHP's manual for <a href=\"http://php.net/manual/en/language.types.string.php\" rel=\"noreferrer\">proper string construction</a> and for the <a href=\"http://php.net/manual/en/language.operators.string.php\" rel=\"noreferrer\">concatenation operators</a>.</p>\n\n<p>Now, the <a href=\"https://codex.wordpress.org/Function_Reference/_e\" rel=\"noreferrer\"><code>_e()</code></a> function is a language translation string. That means it is supposed to be replaceable by translations into other languages. Since you have a dynamic component, that translation could be tricky. In fact, what you are doing now <a href=\"https://codex.wordpress.org/I18n_for_WordPress_Developers#Placeholders\" rel=\"noreferrer\">is exactly what the Codex instructs you not to do.</a> What you want to do instead is provide a stable string for translation then switch in whatever dynamic components you need. </p>\n\n<pre><code>printf(\n __( \n 'The page you are looking for is not here. Why donβt you try the <a href=\"%s\">homepage</a>?', \n 'braveandco' \n ),\n esc_url( home_url( '/' ) )\n);\n</code></pre>\n"
}
] |
2015/10/27
|
[
"https://wordpress.stackexchange.com/questions/206712",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82041/"
] |
How do I put the homepage link ? Right now it's not correct.
```
<p><?php _e( 'The page you are looking for is not here. Why donβt you try the <a href="<?php echo esc_url( home_url( '/' ) ); ?>">homepage</a>?', 'braveandco' ); ?></p>
```
|
You are using PHP inside a single quote and a malformed one at that. That won't work. Step one is to get that string right:
```
_e( 'The page you are looking for is not here. Why donβt you try the <a href="'.esc_url( home_url( '/' ) ).'">homepage</a>?', 'braveandco' );
```
That is pure PHP. Check PHP's manual for [proper string construction](http://php.net/manual/en/language.types.string.php) and for the [concatenation operators](http://php.net/manual/en/language.operators.string.php).
Now, the [`_e()`](https://codex.wordpress.org/Function_Reference/_e) function is a language translation string. That means it is supposed to be replaceable by translations into other languages. Since you have a dynamic component, that translation could be tricky. In fact, what you are doing now [is exactly what the Codex instructs you not to do.](https://codex.wordpress.org/I18n_for_WordPress_Developers#Placeholders) What you want to do instead is provide a stable string for translation then switch in whatever dynamic components you need.
```
printf(
__(
'The page you are looking for is not here. Why donβt you try the <a href="%s">homepage</a>?',
'braveandco'
),
esc_url( home_url( '/' ) )
);
```
|
206,719 |
<p>When I remove get_header() from 404 page, my css doesnt work.</p>
<pre><code> <?php
/**
* The template for displaying 404 pages (Not Found)
*
* @package WordPress
* @subpackage Twenty_Fourteen
* @since Twenty Fourteen 1.0
*/
?>
<div class="page-content">
<h1 class="page-title"><?php _e( 'Not Found', 'twentyfourteen' ); ?></h1>
<p><?php _e( 'It looks like nothing was found at this location. Maybe try a search?', 'twentyfourteen' ); ?></p>
</div>
</code></pre>
<p>css </p>
<pre><code> .page-content {
max-width: 300px;
margin: 0 auto;
text-align: center;
}
.page-title {
color: red;
}
</code></pre>
|
[
{
"answer_id": 206722,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": false,
"text": "<p>Of course it doesn't. When you remove <code>get_header()</code> you also remove the code that loads the CSS files, not to mention that you remove large blocks of necessary HTML markup. The template you've posted above is very, very broken.</p>\n\n<p>You've also left out <code>get_footer()</code> which will most likely leave your markup broken as well.</p>\n\n<p>Instead of leaving out <a href=\"https://codex.wordpress.org/Function_Reference/get_header\" rel=\"nofollow\"><code>get_header()</code></a> use it with an optional argument to load a truncated header file for your 404 page:</p>\n\n<blockquote>\n <p>Description</p>\n \n <p>Includes the header.php template file from your current theme's\n directory. If a name is specified then a specialised header\n header-{name}.php will be included.</p>\n \n <p>If the theme contains no header.php file then the header from the\n default theme wp-includes/theme-compat/header.php will be included.</p>\n</blockquote>\n\n<p>For example (from the Codex): </p>\n\n<pre><code>if ( is_home() ) :\n get_header( 'home' );\nelseif ( is_404() ) :\n get_header( '404' );\nelse :\n get_header();\nendif;\n</code></pre>\n\n<p>In your template, you only need <code>get_header( '404' );</code> plus a PHP file named <code>header-404.php</code> containing whatever you want to display.</p>\n"
},
{
"answer_id": 206941,
"author": "vol4ikman",
"author_id": 31075,
"author_profile": "https://wordpress.stackexchange.com/users/31075",
"pm_score": 0,
"selected": false,
"text": "<p>Minimum template structure is:</p>\n\n<p>1) get_header()</p>\n\n<p>2) get_footer()</p>\n\n<p>You can not touch this functions, this is a heart of each template/page/single/category...</p>\n"
}
] |
2015/10/27
|
[
"https://wordpress.stackexchange.com/questions/206719",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82041/"
] |
When I remove get\_header() from 404 page, my css doesnt work.
```
<?php
/**
* The template for displaying 404 pages (Not Found)
*
* @package WordPress
* @subpackage Twenty_Fourteen
* @since Twenty Fourteen 1.0
*/
?>
<div class="page-content">
<h1 class="page-title"><?php _e( 'Not Found', 'twentyfourteen' ); ?></h1>
<p><?php _e( 'It looks like nothing was found at this location. Maybe try a search?', 'twentyfourteen' ); ?></p>
</div>
```
css
```
.page-content {
max-width: 300px;
margin: 0 auto;
text-align: center;
}
.page-title {
color: red;
}
```
|
Of course it doesn't. When you remove `get_header()` you also remove the code that loads the CSS files, not to mention that you remove large blocks of necessary HTML markup. The template you've posted above is very, very broken.
You've also left out `get_footer()` which will most likely leave your markup broken as well.
Instead of leaving out [`get_header()`](https://codex.wordpress.org/Function_Reference/get_header) use it with an optional argument to load a truncated header file for your 404 page:
>
> Description
>
>
> Includes the header.php template file from your current theme's
> directory. If a name is specified then a specialised header
> header-{name}.php will be included.
>
>
> If the theme contains no header.php file then the header from the
> default theme wp-includes/theme-compat/header.php will be included.
>
>
>
For example (from the Codex):
```
if ( is_home() ) :
get_header( 'home' );
elseif ( is_404() ) :
get_header( '404' );
else :
get_header();
endif;
```
In your template, you only need `get_header( '404' );` plus a PHP file named `header-404.php` containing whatever you want to display.
|
206,721 |
<p>I'm trying to get top 10 users in my wordpress blog based on user meta value.</p>
<p>I've tried few methods & finally able to get just top one user using below wpdb query. But clueless, how we can get top 10 users.</p>
<pre><code>$top10alltime = $wpdb->get_row( "SELECT MAX( CAST( meta_value AS UNSIGNED ) ) AS top_user FROM $wpdb->usermeta WHERE meta_key = 'alltimeusers'" );
echo $top10alltime->top_user;
</code></pre>
<p>Is <code>$wpdb</code> is right for this purpose? Or is there any other solution to get this done? using <code>WP_User_Query</code>?</p>
<p>I've tried something with <code>WP_User_Query</code>.</p>
<pre><code>foreach ( $users as $var => $order ) {
$query->query(
array(
'count_total' => false,
'meta_key' => 'todayuserclicks',
'orderby' => 'meta_value',
'fields' => 'ID',
'number' => 10,
'order' => $order,
)
);
</code></pre>
<p>I can't get this done after this .. how can we do this?</p>
|
[
{
"answer_id": 206722,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": false,
"text": "<p>Of course it doesn't. When you remove <code>get_header()</code> you also remove the code that loads the CSS files, not to mention that you remove large blocks of necessary HTML markup. The template you've posted above is very, very broken.</p>\n\n<p>You've also left out <code>get_footer()</code> which will most likely leave your markup broken as well.</p>\n\n<p>Instead of leaving out <a href=\"https://codex.wordpress.org/Function_Reference/get_header\" rel=\"nofollow\"><code>get_header()</code></a> use it with an optional argument to load a truncated header file for your 404 page:</p>\n\n<blockquote>\n <p>Description</p>\n \n <p>Includes the header.php template file from your current theme's\n directory. If a name is specified then a specialised header\n header-{name}.php will be included.</p>\n \n <p>If the theme contains no header.php file then the header from the\n default theme wp-includes/theme-compat/header.php will be included.</p>\n</blockquote>\n\n<p>For example (from the Codex): </p>\n\n<pre><code>if ( is_home() ) :\n get_header( 'home' );\nelseif ( is_404() ) :\n get_header( '404' );\nelse :\n get_header();\nendif;\n</code></pre>\n\n<p>In your template, you only need <code>get_header( '404' );</code> plus a PHP file named <code>header-404.php</code> containing whatever you want to display.</p>\n"
},
{
"answer_id": 206941,
"author": "vol4ikman",
"author_id": 31075,
"author_profile": "https://wordpress.stackexchange.com/users/31075",
"pm_score": 0,
"selected": false,
"text": "<p>Minimum template structure is:</p>\n\n<p>1) get_header()</p>\n\n<p>2) get_footer()</p>\n\n<p>You can not touch this functions, this is a heart of each template/page/single/category...</p>\n"
}
] |
2015/10/27
|
[
"https://wordpress.stackexchange.com/questions/206721",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74094/"
] |
I'm trying to get top 10 users in my wordpress blog based on user meta value.
I've tried few methods & finally able to get just top one user using below wpdb query. But clueless, how we can get top 10 users.
```
$top10alltime = $wpdb->get_row( "SELECT MAX( CAST( meta_value AS UNSIGNED ) ) AS top_user FROM $wpdb->usermeta WHERE meta_key = 'alltimeusers'" );
echo $top10alltime->top_user;
```
Is `$wpdb` is right for this purpose? Or is there any other solution to get this done? using `WP_User_Query`?
I've tried something with `WP_User_Query`.
```
foreach ( $users as $var => $order ) {
$query->query(
array(
'count_total' => false,
'meta_key' => 'todayuserclicks',
'orderby' => 'meta_value',
'fields' => 'ID',
'number' => 10,
'order' => $order,
)
);
```
I can't get this done after this .. how can we do this?
|
Of course it doesn't. When you remove `get_header()` you also remove the code that loads the CSS files, not to mention that you remove large blocks of necessary HTML markup. The template you've posted above is very, very broken.
You've also left out `get_footer()` which will most likely leave your markup broken as well.
Instead of leaving out [`get_header()`](https://codex.wordpress.org/Function_Reference/get_header) use it with an optional argument to load a truncated header file for your 404 page:
>
> Description
>
>
> Includes the header.php template file from your current theme's
> directory. If a name is specified then a specialised header
> header-{name}.php will be included.
>
>
> If the theme contains no header.php file then the header from the
> default theme wp-includes/theme-compat/header.php will be included.
>
>
>
For example (from the Codex):
```
if ( is_home() ) :
get_header( 'home' );
elseif ( is_404() ) :
get_header( '404' );
else :
get_header();
endif;
```
In your template, you only need `get_header( '404' );` plus a PHP file named `header-404.php` containing whatever you want to display.
|
206,724 |
<p>I try to create a page that shows my posts (a page different than the "posts page" defined in wp-admin).</p>
<p>When I copy my <code>index.php</code> into this new page and add </p>
<pre><code><?php query_posts('post_type=post&posts_per_page=5&paged='.get_query_var('paged')); ?>
</code></pre>
<p>above the </p>
<pre><code> <?php if ( have_posts() ) : ?>
...
...
</code></pre>
<p>then everything works fine - my posts are shown. If I try to put </p>
<pre><code> <?php get_posts(); ?>
</code></pre>
<p>instead of</p>
<pre><code><?php query_posts('post_type=post&posts_per_page=5&paged='.get_query_var('paged')); ?>
</code></pre>
<p>the posts are not showing.</p>
<p>Since everyone suggests that <code>get_posts()</code> is preferable in general over <code>query_posts()</code>, I wonder how can I have the posts showing, using <code>get_posts()</code>.</p>
|
[
{
"answer_id": 206743,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>Every page has a \"main query\" which is run before the template is loaded. The results of the main query are how WordPress determines what template to load. The standard Loop operates on the data contained in the main query, this is why it seems to just magically \"work\" without you having to explicitly query something yourself.</p>\n\n<p><code>query_posts</code> overwrites the contents of that main query. This is why you shouldn't use <code>query_posts</code>- you're changing the query results after the template is loaded, which can have unexpected consequences. <code>pre_get_posts</code> is the preferred way to modify the main query, it runs before the main query happens, so that everything that follows is operating on the correct set of data.</p>\n\n<p><code>get_posts</code> and <code>WP_Query</code> are for running <em>additional</em> queries, separate from the main query. You have to assign the results to a variable, and run some sort of loop on those results. Your use of <code>get_posts</code> is doing nothing, because you've done nothing with the results of that query.</p>\n"
},
{
"answer_id": 206800,
"author": "IXN",
"author_id": 80031,
"author_profile": "https://wordpress.stackexchange.com/users/80031",
"pm_score": 1,
"selected": true,
"text": "<p>The thing is that, contrary to popular belief, <code>pre_get_posts</code> does not work for single Page requests.<a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow\">1</a> Not even for is_front_page().</p>\n\n<p>As for <code>get posts()</code>, in order to work I needed to use a syntax like:</p>\n\n<pre><code><?php global $post;\n$myposts = get_posts();\nforeach( $myposts as $post ) : setup_postdata($post); ?>\n ...\n<?php endforeach; \nwp_reset_postdata(); ?>\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code><?php get_posts(); while ( have_posts() ) : the_post(); ?>\n...\n</code></pre>\n"
}
] |
2015/10/27
|
[
"https://wordpress.stackexchange.com/questions/206724",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80031/"
] |
I try to create a page that shows my posts (a page different than the "posts page" defined in wp-admin).
When I copy my `index.php` into this new page and add
```
<?php query_posts('post_type=post&posts_per_page=5&paged='.get_query_var('paged')); ?>
```
above the
```
<?php if ( have_posts() ) : ?>
...
...
```
then everything works fine - my posts are shown. If I try to put
```
<?php get_posts(); ?>
```
instead of
```
<?php query_posts('post_type=post&posts_per_page=5&paged='.get_query_var('paged')); ?>
```
the posts are not showing.
Since everyone suggests that `get_posts()` is preferable in general over `query_posts()`, I wonder how can I have the posts showing, using `get_posts()`.
|
The thing is that, contrary to popular belief, `pre_get_posts` does not work for single Page requests.[1](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) Not even for is\_front\_page().
As for `get posts()`, in order to work I needed to use a syntax like:
```
<?php global $post;
$myposts = get_posts();
foreach( $myposts as $post ) : setup_postdata($post); ?>
...
<?php endforeach;
wp_reset_postdata(); ?>
```
instead of
```
<?php get_posts(); while ( have_posts() ) : the_post(); ?>
...
```
|
206,732 |
<p>I have a rather silly situation.</p>
<p>I tried <a href="https://perishablepress.com/quickly-disable-or-enable-all-wordpress-plugins-via-the-database/" rel="nofollow">this query </a></p>
<pre><code>UPDATE wp_options SET option_value = 'a:0:{}' WHERE option_name = 'active_plugins';
</code></pre>
<p>which disabled all my plugins. I was testing some issues on my site and this was the only solution to disable them. I had no wp admin access.</p>
<p>The problem is that after I add the old code back in "active_plugins" and disabled or enabled any (random) plugins, the site crashes and the "active_plugins" entry becomes blank.</p>
<p>At the moment, the only solution that I see is to overwrite the wp_options table. Using a backup for the whole database is not a good solution due to the fact that the site is an active WooCommerce based site with daily orders. </p>
<p><strong>My question:</strong> Is there something important in wp_options that might get lost if I put an older version of it in the database?</p>
|
[
{
"answer_id": 206733,
"author": "Bruno Cantuaria",
"author_id": 65717,
"author_profile": "https://wordpress.stackexchange.com/users/65717",
"pm_score": 0,
"selected": false,
"text": "<p>Options store all relevant options of your website, including from plugins and themes.</p>\n\n<p>A good way to debug plugins, is using FTP and renaming 'plugins' folder or renaming the folder of the plugin which is throwing the error (checking the PHP Error Log should be helpful to detect which one is)</p>\n"
},
{
"answer_id": 206736,
"author": "Aravona",
"author_id": 49852,
"author_profile": "https://wordpress.stackexchange.com/users/49852",
"pm_score": 3,
"selected": true,
"text": "<p>The <code>wp_options</code> table holds a lot of information, whether you deem it important or not really depends on what plugins and information you have set up on your website and how important your website is to you.</p>\n\n<p>For example as you've noticed it can hold the information for your active plugins, if you activate an important plugin and then rollback to a database from a week prior, you'll not have that plugin active and that could cause issues - think security plugins, or user enhancement plugins, they're important to you and your users. Even with 500 rows displayed per page in PHPMyAdmin I have 7 pages of data in <code>wp_options</code> I'd say for myself that it's all important for my website - it's security settings for the most part. </p>\n\n<p>The table also holds some crutial information like your site url, home url etc. If you don't have these set up in your <code>wp-config.php</code> file then removing them <em>may</em> cause you some issues too. Also if you've changed the admin email through <code>wp_options</code> and rollback to an older database copy without this change well, it's not the end of the world you can edit it again but if you have plugins that utilise it then they may play up too. It's just unnecessary hassle I think to have to re-edit these things, not a disaster though.</p>\n\n<p>It's better to always back up your database just prior to making changes, that way you can always rollback to a version that's same day to your editing.</p>\n"
}
] |
2015/10/27
|
[
"https://wordpress.stackexchange.com/questions/206732",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31610/"
] |
I have a rather silly situation.
I tried [this query](https://perishablepress.com/quickly-disable-or-enable-all-wordpress-plugins-via-the-database/)
```
UPDATE wp_options SET option_value = 'a:0:{}' WHERE option_name = 'active_plugins';
```
which disabled all my plugins. I was testing some issues on my site and this was the only solution to disable them. I had no wp admin access.
The problem is that after I add the old code back in "active\_plugins" and disabled or enabled any (random) plugins, the site crashes and the "active\_plugins" entry becomes blank.
At the moment, the only solution that I see is to overwrite the wp\_options table. Using a backup for the whole database is not a good solution due to the fact that the site is an active WooCommerce based site with daily orders.
**My question:** Is there something important in wp\_options that might get lost if I put an older version of it in the database?
|
The `wp_options` table holds a lot of information, whether you deem it important or not really depends on what plugins and information you have set up on your website and how important your website is to you.
For example as you've noticed it can hold the information for your active plugins, if you activate an important plugin and then rollback to a database from a week prior, you'll not have that plugin active and that could cause issues - think security plugins, or user enhancement plugins, they're important to you and your users. Even with 500 rows displayed per page in PHPMyAdmin I have 7 pages of data in `wp_options` I'd say for myself that it's all important for my website - it's security settings for the most part.
The table also holds some crutial information like your site url, home url etc. If you don't have these set up in your `wp-config.php` file then removing them *may* cause you some issues too. Also if you've changed the admin email through `wp_options` and rollback to an older database copy without this change well, it's not the end of the world you can edit it again but if you have plugins that utilise it then they may play up too. It's just unnecessary hassle I think to have to re-edit these things, not a disaster though.
It's better to always back up your database just prior to making changes, that way you can always rollback to a version that's same day to your editing.
|
206,750 |
<p>I would like to create a page template that will have two containers. Left one should be for text (it is a multilingual website so that is why I need a page template), and the right side should be for images which are the same for all languages.
My question is, what do I have to create so a client can insert and edit images as he pleases?
Do I have to create a post, a page or something else? It must not be indexed as itself. I am interested in "the right Wordpress way"</p>
<pre><code><div class="col-md-6">
<?php the_content(); ?>
</div>
<div class="col-md-6">
<?php // include images ?>
</div>
</code></pre>
|
[
{
"answer_id": 206777,
"author": "Dava Gordon",
"author_id": 82586,
"author_profile": "https://wordpress.stackexchange.com/users/82586",
"pm_score": 0,
"selected": false,
"text": "<p>As woocommerce is basically just posts have you not tried single-productID.php so single-234.php</p>\n"
},
{
"answer_id": 206942,
"author": "Scriptonomy",
"author_id": 82166,
"author_profile": "https://wordpress.stackexchange.com/users/82166",
"pm_score": 2,
"selected": false,
"text": "<p>Override the template with a <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include\" rel=\"nofollow\">template_include</a> filter.</p>\n"
},
{
"answer_id": 270565,
"author": "gfirem",
"author_id": 97324,
"author_profile": "https://wordpress.stackexchange.com/users/97324",
"pm_score": 1,
"selected": false,
"text": "<p>you need to check the last specifications from woocommerce to override his template files.</p>\n\n<p><a href=\"https://docs.woocommerce.com/document/template-structure/\" rel=\"nofollow noreferrer\">https://docs.woocommerce.com/document/template-structure/</a> </p>\n\n<p>The last time i did it, i copy the template file with the structure of the folder from the woo plugins template directory under the active theme inside a folder named woocommerce with the same structure. You can get more info in the above link. </p>\n"
}
] |
2015/10/27
|
[
"https://wordpress.stackexchange.com/questions/206750",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47357/"
] |
I would like to create a page template that will have two containers. Left one should be for text (it is a multilingual website so that is why I need a page template), and the right side should be for images which are the same for all languages.
My question is, what do I have to create so a client can insert and edit images as he pleases?
Do I have to create a post, a page or something else? It must not be indexed as itself. I am interested in "the right Wordpress way"
```
<div class="col-md-6">
<?php the_content(); ?>
</div>
<div class="col-md-6">
<?php // include images ?>
</div>
```
|
Override the template with a [template\_include](https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include) filter.
|
206,771 |
<p>The WC_Order_Item_Meta::get_formatted() function returns terms array of the order.
Each term is an array of three things:</p>
<pre><code>'key' => $meta->key // attribute key
'label' => wc_attribute_label( $attribute_key, $this->product ) // attribute label
'value' => apply_filters( 'woocommerce_order_item_display_meta_value', $meta->value ) // term value
</code></pre>
<p>Also I need term slug, how do I can get the slug of the term if I know attribute key/attribute label/term value??</p>
|
[
{
"answer_id": 206774,
"author": "Scriptonomy",
"author_id": 82166,
"author_profile": "https://wordpress.stackexchange.com/users/82166",
"pm_score": 0,
"selected": false,
"text": "<p>This is the output of the function:</p>\n\n<pre><code>array(\n 'pa_size' => array(\n 'label' => 'Size',\n 'value' => 'Medium',\n )\n )\n</code></pre>\n\n<p>You get the slug like this:</p>\n\n<pre><code>$terms = WC_Order_Item_Meta::get_formatted();\nforeach($terms as $slug => $term){\n\n}\n</code></pre>\n"
},
{
"answer_id": 206775,
"author": "Dava Gordon",
"author_id": 82586,
"author_profile": "https://wordpress.stackexchange.com/users/82586",
"pm_score": -1,
"selected": false,
"text": "<pre><code>$term = get_term_by( '1', '2', '3' );\n</code></pre>\n\n<ol>\n<li><p>Replace with what you are trying to retrieve by so 'name' or 'slug' or 'ID'</p></li>\n<li><p>Your term label </p></li>\n<li><p>The taxonomy so if you wanted to search by post category you would put 'category'</p></li>\n</ol>\n"
},
{
"answer_id": 206787,
"author": "Sevi",
"author_id": 82584,
"author_profile": "https://wordpress.stackexchange.com/users/82584",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, I found solution:</p>\n\n<pre><code>$slug = '';\n$item_ = $this->item['item_meta'];\nforeach ($item_ as $meta_ => $term_)\n{\n if(substr($meta_,0,3) == 'pa_' && $meta_ == $meta->key)\n {\n $slug = $term_[0];\n break;\n }\n}\n\n$formatted_meta[ $meta_id ] = array(\n 'key' => $meta->key,\n 'label' => wc_attribute_label( $attribute_key, $this->product ),\n 'value' => apply_filters( 'woocommerce_order_item_display_meta_value', $meta->value ),\n 'slug' => $slug,\n);\n</code></pre>\n"
}
] |
2015/10/27
|
[
"https://wordpress.stackexchange.com/questions/206771",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82584/"
] |
The WC\_Order\_Item\_Meta::get\_formatted() function returns terms array of the order.
Each term is an array of three things:
```
'key' => $meta->key // attribute key
'label' => wc_attribute_label( $attribute_key, $this->product ) // attribute label
'value' => apply_filters( 'woocommerce_order_item_display_meta_value', $meta->value ) // term value
```
Also I need term slug, how do I can get the slug of the term if I know attribute key/attribute label/term value??
|
This is the output of the function:
```
array(
'pa_size' => array(
'label' => 'Size',
'value' => 'Medium',
)
)
```
You get the slug like this:
```
$terms = WC_Order_Item_Meta::get_formatted();
foreach($terms as $slug => $term){
}
```
|
206,789 |
<p>I'm trying to add some custom JS functionality to the default "post" editing screen that depends upon TinyMCE being instantiated and ready to rock. If I try to make the changes before TinyMCE is set up, I (obviously) receive JS errors.</p>
<p>Without needing to modify any core files, and ideally using JS/jQuery events alone (i.e. not PHP/WP hooks/filters or polling with JS' <code>setInterval()</code>), <strong>is there a way to detect when TinyMCE is ready?</strong></p>
|
[
{
"answer_id": 206814,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 3,
"selected": false,
"text": "<p>Unless your WP version is truly ancient, you should be able to use the <code>tinymce-editor-init</code> event triggered on editor <code>init</code> by \"wp-includes/js/tinymce/plugins/wordpress/plugin.js\", eg (assuming your script is loading after jQuery):</p>\n\n<pre><code>jQuery( document ).on( 'tinymce-editor-init', function( event, editor ) {\n // Blah.\n});\n</code></pre>\n"
},
{
"answer_id": 206818,
"author": "1991wp",
"author_id": 80381,
"author_profile": "https://wordpress.stackexchange.com/users/80381",
"pm_score": 1,
"selected": false,
"text": "<p>I have not tested this, but it should work:</p>\n\n<pre><code>is_tinyMCE_active = false;\nif ( typeof( tinyMCE) != \"undefined\" ) {\n if ( tinyMCE.activeEditor == null || tinyMCE.activeEditor.isHidden() != false ) {\n is_tinyMCE_active = true;\n }\n}\n</code></pre>\n"
}
] |
2015/10/27
|
[
"https://wordpress.stackexchange.com/questions/206789",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10388/"
] |
I'm trying to add some custom JS functionality to the default "post" editing screen that depends upon TinyMCE being instantiated and ready to rock. If I try to make the changes before TinyMCE is set up, I (obviously) receive JS errors.
Without needing to modify any core files, and ideally using JS/jQuery events alone (i.e. not PHP/WP hooks/filters or polling with JS' `setInterval()`), **is there a way to detect when TinyMCE is ready?**
|
Unless your WP version is truly ancient, you should be able to use the `tinymce-editor-init` event triggered on editor `init` by "wp-includes/js/tinymce/plugins/wordpress/plugin.js", eg (assuming your script is loading after jQuery):
```
jQuery( document ).on( 'tinymce-editor-init', function( event, editor ) {
// Blah.
});
```
|
206,810 |
<p>Can any one re-write this SQL query to perform better? </p>
<p>At present this query takes about 29 seconds to execute in <strong>BlueHost</strong> server while it takes 6 seconds in <strong>HostGator</strong>.com server.</p>
<p>My intention is to delete all records exists in <strong>wp_postmeta</strong> table of post type=<strong>'attachment'</strong> and with meta_key='_<strong>mycbgenie_managed_by</strong><code>
</code>'</p>
<pre><code>DELETE FROM wp_postmeta WHERE post_id IN
( SELECT ID FROM wp_posts
WHERE post_type = 'attachment'
AND post_parent IN
( SELECT ID FROM
( SELECT ID FROM wp_posts a
LEFT JOIN wp_postmeta b ON (a.ID = b.post_id)
LEFT JOIN wp_postmeta AS mt1 ON (a.ID = mt1.post_id)
WHERE post_type = 'product' AND mt1.meta_key = '_mycbgenie_managed_by'
) AS taskstodelete
)
)
</code></pre>
|
[
{
"answer_id": 206814,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 3,
"selected": false,
"text": "<p>Unless your WP version is truly ancient, you should be able to use the <code>tinymce-editor-init</code> event triggered on editor <code>init</code> by \"wp-includes/js/tinymce/plugins/wordpress/plugin.js\", eg (assuming your script is loading after jQuery):</p>\n\n<pre><code>jQuery( document ).on( 'tinymce-editor-init', function( event, editor ) {\n // Blah.\n});\n</code></pre>\n"
},
{
"answer_id": 206818,
"author": "1991wp",
"author_id": 80381,
"author_profile": "https://wordpress.stackexchange.com/users/80381",
"pm_score": 1,
"selected": false,
"text": "<p>I have not tested this, but it should work:</p>\n\n<pre><code>is_tinyMCE_active = false;\nif ( typeof( tinyMCE) != \"undefined\" ) {\n if ( tinyMCE.activeEditor == null || tinyMCE.activeEditor.isHidden() != false ) {\n is_tinyMCE_active = true;\n }\n}\n</code></pre>\n"
}
] |
2015/10/28
|
[
"https://wordpress.stackexchange.com/questions/206810",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80505/"
] |
Can any one re-write this SQL query to perform better?
At present this query takes about 29 seconds to execute in **BlueHost** server while it takes 6 seconds in **HostGator**.com server.
My intention is to delete all records exists in **wp\_postmeta** table of post type=**'attachment'** and with meta\_key='\_**mycbgenie\_managed\_by**'
```
DELETE FROM wp_postmeta WHERE post_id IN
( SELECT ID FROM wp_posts
WHERE post_type = 'attachment'
AND post_parent IN
( SELECT ID FROM
( SELECT ID FROM wp_posts a
LEFT JOIN wp_postmeta b ON (a.ID = b.post_id)
LEFT JOIN wp_postmeta AS mt1 ON (a.ID = mt1.post_id)
WHERE post_type = 'product' AND mt1.meta_key = '_mycbgenie_managed_by'
) AS taskstodelete
)
)
```
|
Unless your WP version is truly ancient, you should be able to use the `tinymce-editor-init` event triggered on editor `init` by "wp-includes/js/tinymce/plugins/wordpress/plugin.js", eg (assuming your script is loading after jQuery):
```
jQuery( document ).on( 'tinymce-editor-init', function( event, editor ) {
// Blah.
});
```
|
206,829 |
<p>I was accidentally using <code>is_admin()</code> to check if a user was an admin and found out that function is not checking that. So I looked for another one and I found <code>is_super_admin()</code> but that checks if you are a admin of a network of sites or owner of a single WordPress install. I have a network site and I want to know if the user is the owner of the blog. I do not want to use roles. I want to check if the user is the owner of the blog. </p>
|
[
{
"answer_id": 206814,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 3,
"selected": false,
"text": "<p>Unless your WP version is truly ancient, you should be able to use the <code>tinymce-editor-init</code> event triggered on editor <code>init</code> by \"wp-includes/js/tinymce/plugins/wordpress/plugin.js\", eg (assuming your script is loading after jQuery):</p>\n\n<pre><code>jQuery( document ).on( 'tinymce-editor-init', function( event, editor ) {\n // Blah.\n});\n</code></pre>\n"
},
{
"answer_id": 206818,
"author": "1991wp",
"author_id": 80381,
"author_profile": "https://wordpress.stackexchange.com/users/80381",
"pm_score": 1,
"selected": false,
"text": "<p>I have not tested this, but it should work:</p>\n\n<pre><code>is_tinyMCE_active = false;\nif ( typeof( tinyMCE) != \"undefined\" ) {\n if ( tinyMCE.activeEditor == null || tinyMCE.activeEditor.isHidden() != false ) {\n is_tinyMCE_active = true;\n }\n}\n</code></pre>\n"
}
] |
2015/10/28
|
[
"https://wordpress.stackexchange.com/questions/206829",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29247/"
] |
I was accidentally using `is_admin()` to check if a user was an admin and found out that function is not checking that. So I looked for another one and I found `is_super_admin()` but that checks if you are a admin of a network of sites or owner of a single WordPress install. I have a network site and I want to know if the user is the owner of the blog. I do not want to use roles. I want to check if the user is the owner of the blog.
|
Unless your WP version is truly ancient, you should be able to use the `tinymce-editor-init` event triggered on editor `init` by "wp-includes/js/tinymce/plugins/wordpress/plugin.js", eg (assuming your script is loading after jQuery):
```
jQuery( document ).on( 'tinymce-editor-init', function( event, editor ) {
// Blah.
});
```
|
206,830 |
<p>Hi my client need to add password protect page in wordpress. So i make the visibility of page as password protect and it is working correctly.
But client is giving a series of password .He is given password 2314 to 2335 .So the password is any number in between 2314 to 2335 .Now what i do? Is there any method or call to solve this? Any hook is there ?</p>
|
[
{
"answer_id": 206865,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<p><em>Here's just a demo test for fun, just to see if this might be possible:</em></p>\n\n<h2>Demo</h2>\n\n<p>First we set the post's password, the usual way:</p>\n\n<p><a href=\"https://i.stack.imgur.com/1zKPe.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/1zKPe.jpg\" alt=\"password\"></a></p>\n\n<p>Then we create a <em>custom field</em> called <code>wpse_extra_passwords</code> that takes comma seperated passwords:</p>\n\n<p><a href=\"https://i.stack.imgur.com/lyZr6.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/lyZr6.jpg\" alt=\"extra passwords\"></a></p>\n\n<p>These are the extra passwords for that post.</p>\n\n<p>Let's define the following helper function, based on the <code>post_password_required()</code> core function:</p>\n\n<pre><code>/**\n * Helper function, check password + extra passwords\n */\nfunction wpse_post_password_required( $post = null ) \n{\n $post = get_post($post);\n\n if ( empty( $post->post_password ) )\n return false;\n\n if ( ! isset( $_COOKIE['wp-postpass_' . COOKIEHASH] ) )\n return true;\n\n require_once ABSPATH . WPINC . '/class-phpass.php';\n $hasher = new PasswordHash( 8, true );\n\n $hash = wp_unslash( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] );\n if ( 0 !== strpos( $hash, '$P$B' ) )\n return true;\n\n // Check the current password\n if( $hasher->CheckPassword( $post->post_password, $hash ) )\n return false;\n\n // Fetch extra passwords\n if( ! $extra_passwords = get_post_meta( $post->ID, 'wpse_extra_passwords', true ) )\n return true;\n\n // Check these extra passwords \n $extra = explode( ',', $extra_passwords ); \n foreach( (array) $extra as $password )\n {\n $password = trim( $password );\n if( ! empty( $password ) && $hasher->CheckPassword( $password, $hash ) )\n return false; \n } \n return true;\n}\n</code></pre>\n\n<p>Then we hook into the <code>the_password_form</code> filter and target the single post object in the main loop:</p>\n\n<pre><code>/**\n * Support extra post passwords for single posts in the main loop\n */\nadd_filter( 'the_password_form', function( $output )\n{\n if( ! is_single() || ! in_the_loop() || did_action( 'the_password_form' ) )\n return $output;\n\n $post = get_post();\n\n // Display password form if none of the passwords matches: \n if( wpse_post_password_required( $post ) )\n return $output;\n\n // Get the current password\n $password = $post->post_password;\n\n // Temporary remove it\n $post->post_password = '';\n\n // Fetch the content\n $content = get_the_content();\n\n // Set the password back\n $post->post_password = $password;\n\n return $content;\n} );\n</code></pre>\n\n<p>Hopefully you can test it and play with it further.</p>\n\n<h2>Notes</h2>\n\n<p>You mentioned passwords like 2314. It's very easy to write a program that can guess simple passwords like that. So I used a little bit stronger passwords in this demo.</p>\n"
},
{
"answer_id": 317655,
"author": "am_",
"author_id": 118059,
"author_profile": "https://wordpress.stackexchange.com/users/118059",
"pm_score": 0,
"selected": false,
"text": "<p>You could also use a plugin for that:\n<a href=\"https://wordpress.org/plugins/multiple-post-passwords/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/multiple-post-passwords/</a></p>\n\n<p>And yes, having a series of numbers as passwords is a bad idea ;)</p>\n"
}
] |
2015/10/28
|
[
"https://wordpress.stackexchange.com/questions/206830",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70398/"
] |
Hi my client need to add password protect page in wordpress. So i make the visibility of page as password protect and it is working correctly.
But client is giving a series of password .He is given password 2314 to 2335 .So the password is any number in between 2314 to 2335 .Now what i do? Is there any method or call to solve this? Any hook is there ?
|
*Here's just a demo test for fun, just to see if this might be possible:*
Demo
----
First we set the post's password, the usual way:
[](https://i.stack.imgur.com/1zKPe.jpg)
Then we create a *custom field* called `wpse_extra_passwords` that takes comma seperated passwords:
[](https://i.stack.imgur.com/lyZr6.jpg)
These are the extra passwords for that post.
Let's define the following helper function, based on the `post_password_required()` core function:
```
/**
* Helper function, check password + extra passwords
*/
function wpse_post_password_required( $post = null )
{
$post = get_post($post);
if ( empty( $post->post_password ) )
return false;
if ( ! isset( $_COOKIE['wp-postpass_' . COOKIEHASH] ) )
return true;
require_once ABSPATH . WPINC . '/class-phpass.php';
$hasher = new PasswordHash( 8, true );
$hash = wp_unslash( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] );
if ( 0 !== strpos( $hash, '$P$B' ) )
return true;
// Check the current password
if( $hasher->CheckPassword( $post->post_password, $hash ) )
return false;
// Fetch extra passwords
if( ! $extra_passwords = get_post_meta( $post->ID, 'wpse_extra_passwords', true ) )
return true;
// Check these extra passwords
$extra = explode( ',', $extra_passwords );
foreach( (array) $extra as $password )
{
$password = trim( $password );
if( ! empty( $password ) && $hasher->CheckPassword( $password, $hash ) )
return false;
}
return true;
}
```
Then we hook into the `the_password_form` filter and target the single post object in the main loop:
```
/**
* Support extra post passwords for single posts in the main loop
*/
add_filter( 'the_password_form', function( $output )
{
if( ! is_single() || ! in_the_loop() || did_action( 'the_password_form' ) )
return $output;
$post = get_post();
// Display password form if none of the passwords matches:
if( wpse_post_password_required( $post ) )
return $output;
// Get the current password
$password = $post->post_password;
// Temporary remove it
$post->post_password = '';
// Fetch the content
$content = get_the_content();
// Set the password back
$post->post_password = $password;
return $content;
} );
```
Hopefully you can test it and play with it further.
Notes
-----
You mentioned passwords like 2314. It's very easy to write a program that can guess simple passwords like that. So I used a little bit stronger passwords in this demo.
|
206,845 |
<p>I am trying to display Popular Posts on my website, selected by a mixture of Views and Comment Count. Since views are always way more than Comments, I am multiplying the Comment Count by X, but it doesnt seem to work how I was hoping it would. The Query Result is just ordered by the Meta Value "Views". I assume this is because I would need to calculate the Sum of Views + Comment Count * X and then order by it... But I am not sure how to accomplish this with using only get_posts(). Can somebody point me in the correct direction? :)</p>
<p>This is my Code</p>
<pre><code>$home_top_news = get_posts(
array(
'post_type' => array('post','reviews'),
'post_status' => 'publish',
'numberposts' => '15',
'meta_key' => 'views',
'orderby' => array(
'meta_value_num' => 'DESC',
'(comment_count * 10)' => 'DESC',
),
'date_query' => array(
array(
'after' => '12 days ago'
)
)
)
);
</code></pre>
|
[
{
"answer_id": 206855,
"author": "Bruno Cantuaria",
"author_id": 65717,
"author_profile": "https://wordpress.stackexchange.com/users/65717",
"pm_score": 1,
"selected": false,
"text": "<p>The question seems a bit vague, there a lot of steps creating an API, but I'll try to resume:</p>\n\n<ol>\n<li>Create an interaction page (You can use the wp-ajax or a page template)</li>\n<li>Code the function which will read parameters and execute the code</li>\n<li>Output only the result to browser. You can output json with a code line like:</li>\n</ol>\n\n<p><code>echo json_encode( $result );</code></p>\n"
},
{
"answer_id": 206938,
"author": "vol4ikman",
"author_id": 31075,
"author_profile": "https://wordpress.stackexchange.com/users/31075",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe this will help you\n<a href=\"http://v2.wp-api.org\" rel=\"nofollow\">WPApi</a></p>\n"
},
{
"answer_id": 207067,
"author": "Muntasir Mahmud Aumio",
"author_id": 48345,
"author_profile": "https://wordpress.stackexchange.com/users/48345",
"pm_score": 0,
"selected": false,
"text": "<p>I was able to make a json endpoint with WordPress's rewrite rule API.</p>\n\n<p>Here's how:</p>\n\n<pre><code>// Add custom rewrite rule\n\nfunction test_rewrite_rule() {\n\n add_rewrite_tag( '%movies%', '([^&]+)' );\n add_rewrite_rule( 'movie-api/([^&]+)/?', 'index.php?movies=$matches[1]', 'top' );\n\n}\nadd_action( 'init', 'test_rewrite_rule' );\n\n// outputting the data\n\nfunction test_movie_endpoint_data() {\n\n global $wp_query;\n\n $movie_tag = $wp_query->get( 'movies' );\n\n if ( ! $movie_tag ) {\n return;\n }\n\n if ( $movie_tag == 'all' ) {\n $movie_tag = false;\n }\n\n $movie_data = array();\n\n $args = array(\n 'post_type' => 'movies',\n 'posts_per_page' => 100,\n 'moxie_tag' => esc_attr( $movie_tag ),\n );\n\n $movie_query = new WP_Query( $args );\n if ( $movie_query->have_posts() ) : while ( $movie_query->have_posts() ) : \n $movie_query->the_post();\n\n $movie_data[] = array(\n 'id' => get_the_id(),\n 'title' => get_the_title(),\n 'poster_url' => esc_url( test_get_meta('poster_url') ),\n 'rating' => test_get_meta('rating'), \n 'year' => test_get_meta('year'),\n 'short_description' => test_get_meta('description'),\n );\n endwhile; \n wp_reset_postdata(); \n endif;\n\n wp_send_json( $movie_data );\n\n} \nadd_action( 'template_redirect', 'test_movie_endpoint_data' );\n</code></pre>\n\n<p>But while I try to pull the json data with wordpress's wp_remote_get(), curl or file_get_contents() it's returning NULL.</p>\n\n<p>Any idea what's the best way to get those information on the front end form the end point?</p>\n"
}
] |
2015/10/28
|
[
"https://wordpress.stackexchange.com/questions/206845",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71313/"
] |
I am trying to display Popular Posts on my website, selected by a mixture of Views and Comment Count. Since views are always way more than Comments, I am multiplying the Comment Count by X, but it doesnt seem to work how I was hoping it would. The Query Result is just ordered by the Meta Value "Views". I assume this is because I would need to calculate the Sum of Views + Comment Count \* X and then order by it... But I am not sure how to accomplish this with using only get\_posts(). Can somebody point me in the correct direction? :)
This is my Code
```
$home_top_news = get_posts(
array(
'post_type' => array('post','reviews'),
'post_status' => 'publish',
'numberposts' => '15',
'meta_key' => 'views',
'orderby' => array(
'meta_value_num' => 'DESC',
'(comment_count * 10)' => 'DESC',
),
'date_query' => array(
array(
'after' => '12 days ago'
)
)
)
);
```
|
The question seems a bit vague, there a lot of steps creating an API, but I'll try to resume:
1. Create an interaction page (You can use the wp-ajax or a page template)
2. Code the function which will read parameters and execute the code
3. Output only the result to browser. You can output json with a code line like:
`echo json_encode( $result );`
|
206,852 |
<p>I am using get_post() to call a single Wordpress post using it's post ID. I have successfully managed to pull the content / title of the post but would like to also pull custom fields also.</p>
<p>The code below is how I declare custom fields in a standard wp_query:</p>
<pre><code>$customField = (get_post_meta($post->ID, "_mcf_customField", true));
</code></pre>
<p>And my get_post code below:</p>
<pre><code> $my_id = 401491;
$post_id = get_post($my_id);
$customField = get_post_meta($post_id, "_mcf_customField", true); // I do not think this is correct
$content = $post_id ->post_content;
echo $content;
echo $customField; // No output
</code></pre>
<p>I believe the customField variable above is declared incorrectly, cannot seem to find anything in the Codex that sheds any light though. Does anyone have experience using Custom fields with get_post?</p>
|
[
{
"answer_id": 206853,
"author": "Bruno Cantuaria",
"author_id": 65717,
"author_profile": "https://wordpress.stackexchange.com/users/65717",
"pm_score": 3,
"selected": true,
"text": "<p>You already know the ID, so just use it:</p>\n\n<pre><code>$customField = get_post_meta($my_id, \"_mcf_customField\", true);\n</code></pre>\n\n<p>But only for reference, if you want to get the ID from the object:</p>\n\n<pre><code>$customField = get_post_meta($post_id->ID, \"_mcf_customField\", true);\n</code></pre>\n"
},
{
"answer_id": 357998,
"author": "andyrandy",
"author_id": 181145,
"author_profile": "https://wordpress.stackexchange.com/users/181145",
"pm_score": 1,
"selected": false,
"text": "<p>With ACF, i am able to do this:</p>\n\n<pre><code>$my_field = get_field('my_field', $post->ID);\n</code></pre>\n\n<p>Reference: <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/get_field/</a></p>\n"
}
] |
2015/10/28
|
[
"https://wordpress.stackexchange.com/questions/206852",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71177/"
] |
I am using get\_post() to call a single Wordpress post using it's post ID. I have successfully managed to pull the content / title of the post but would like to also pull custom fields also.
The code below is how I declare custom fields in a standard wp\_query:
```
$customField = (get_post_meta($post->ID, "_mcf_customField", true));
```
And my get\_post code below:
```
$my_id = 401491;
$post_id = get_post($my_id);
$customField = get_post_meta($post_id, "_mcf_customField", true); // I do not think this is correct
$content = $post_id ->post_content;
echo $content;
echo $customField; // No output
```
I believe the customField variable above is declared incorrectly, cannot seem to find anything in the Codex that sheds any light though. Does anyone have experience using Custom fields with get\_post?
|
You already know the ID, so just use it:
```
$customField = get_post_meta($my_id, "_mcf_customField", true);
```
But only for reference, if you want to get the ID from the object:
```
$customField = get_post_meta($post_id->ID, "_mcf_customField", true);
```
|
206,854 |
<p>I'm using the following query to check if user id exists in a custom meta field:</p>
<pre><code>'meta_query' => array(
array(
'key' => 'participantes',
'value' => $user_id,
'compare' => 'IN',
),
)
</code></pre>
<p>The field <code>participantes</code> stores user ids separated by comma, like <code>345,1,34</code>.</p>
<p>This only works when the current user id is the first number in the list.</p>
|
[
{
"answer_id": 206861,
"author": "M-R",
"author_id": 17061,
"author_profile": "https://wordpress.stackexchange.com/users/17061",
"pm_score": 3,
"selected": true,
"text": "<p>I believe, more robust solution would be to allow multiple values of custom field 'participants'. You can store like following</p>\n\n<pre><code>add_post_meta($post_id,'participants','value1');\nadd_post_meta($post_id,'participants','value2');\nadd_post_meta($post_id,'participants','value3');\nadd_post_meta($post_id,'participants','value4');\n</code></pre>\n\n<p>Deletion would be like</p>\n\n<pre><code>delete_post_meta($post_id,'participants','value1');\n</code></pre>\n\n<p>Query will then change to a simpler one.</p>\n\n<pre><code>'meta_query' => array(\n array(\n 'key' => 'participants',\n 'value' => $user_id,\n 'compare' => '=',\n ),\n)\n</code></pre>\n\n<p>In case you would like to go for an array implementation, you can store values as following</p>\n\n<pre><code>$array = array('value1','value2','value3');\nupdate_post_meta($post_id,'participants',$array);\n</code></pre>\n\n<p>And search can be done like </p>\n\n<pre><code>'meta_query' => array(\n array(\n 'key' => 'participants',\n 'value' => '\"'.$userid.'\"',\n 'compare' => 'LIKE',\n ),\n)\n</code></pre>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/85092/like-meta-query\">Source</a> for searching in serialized array</p>\n\n<blockquote>\n <p>This way, it searches for the whole ID, including the double quotes\n before and after it within the serialized array. No false positives\n will be included.</p>\n</blockquote>\n"
},
{
"answer_id": 206869,
"author": "shadylane",
"author_id": 82498,
"author_profile": "https://wordpress.stackexchange.com/users/82498",
"pm_score": 0,
"selected": false,
"text": "<p>Just because the value is a series of IDs separated by commas does not mean it will be recognised as an array. Try the following.</p>\n\n<pre><code>'meta_query' => array(\n array(\n 'key' => 'participantes',\n 'value' => explode( \",\", $user_id),\n 'compare' => 'IN',\n ),\n)\n</code></pre>\n"
}
] |
2015/10/28
|
[
"https://wordpress.stackexchange.com/questions/206854",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38553/"
] |
I'm using the following query to check if user id exists in a custom meta field:
```
'meta_query' => array(
array(
'key' => 'participantes',
'value' => $user_id,
'compare' => 'IN',
),
)
```
The field `participantes` stores user ids separated by comma, like `345,1,34`.
This only works when the current user id is the first number in the list.
|
I believe, more robust solution would be to allow multiple values of custom field 'participants'. You can store like following
```
add_post_meta($post_id,'participants','value1');
add_post_meta($post_id,'participants','value2');
add_post_meta($post_id,'participants','value3');
add_post_meta($post_id,'participants','value4');
```
Deletion would be like
```
delete_post_meta($post_id,'participants','value1');
```
Query will then change to a simpler one.
```
'meta_query' => array(
array(
'key' => 'participants',
'value' => $user_id,
'compare' => '=',
),
)
```
In case you would like to go for an array implementation, you can store values as following
```
$array = array('value1','value2','value3');
update_post_meta($post_id,'participants',$array);
```
And search can be done like
```
'meta_query' => array(
array(
'key' => 'participants',
'value' => '"'.$userid.'"',
'compare' => 'LIKE',
),
)
```
[Source](https://wordpress.stackexchange.com/questions/85092/like-meta-query) for searching in serialized array
>
> This way, it searches for the whole ID, including the double quotes
> before and after it within the serialized array. No false positives
> will be included.
>
>
>
|
206,862 |
<p>I have a function which checks if $_POST is set (a form which submits to the same page). I need to have it initialized before the page is loaded because the function will do a header <strong>redirect</strong> if the validation goes through without errors.</p>
<p>So the function is registered like this:</p>
<pre><code>add_action('init', 'signup_validate_insert');
</code></pre>
<p>And the function itself starts like this:</p>
<pre><code>function signup_validate_insert(){
$errors = false;
if (!empty($_POST['submit_msg'])) {
//validation and stuff
}
</code></pre>
<p>And if there are errors, it returns the errors array:</p>
<pre><code>return $errors;
</code></pre>
<p>When the submit button is pressed, the function registers it as it should, and goes through the validation. I have checked to see that the errors array is being filled in the function. But the variable is not returned! (although I have set "return $errors")</p>
<p>The variable is supposed to be returned to the template, where the errors can be displayed if $errors are not empty.</p>
<p>I have tried switching to <code>add_filter</code> instead, with the same result.</p>
<p>So the question is really how to be able to return this variable - hope you can help!</p>
|
[
{
"answer_id": 206867,
"author": "Balas",
"author_id": 17849,
"author_profile": "https://wordpress.stackexchange.com/users/17849",
"pm_score": 0,
"selected": false,
"text": "<p>See my updated answer, now i tried as per your condition and my url is like now</p>\n\n<pre><code> http://www.example.com/?query=yes\n\nadd_action('init', 'my_cookie');\n\nadd_action('init', 'signup_validate_insert');\n\nfunction signup_validate_insert() {\n if(isset($_REQUEST['query'])) { \n $errors = 'my_error';\n setcookie(\"my_cookie\", $errors, time()+3600); \n wp_redirect(home_url('shortcode-9/'));\n die();\n }\n}\n\nfunction my_cookie() {\n if(isset($_COOKIE['my_cookie'])) {\n\n echo $_COOKIE['my_cookie'];\n }\n}\n\n it is for me working nice. am i right? Reply your thoughts.\n</code></pre>\n"
},
{
"answer_id": 206868,
"author": "Steven",
"author_id": 1447,
"author_profile": "https://wordpress.stackexchange.com/users/1447",
"pm_score": 0,
"selected": false,
"text": "<p>If I remember correctly, unless you specify a POST submission, it will use GET as default.<br>\nSo using <code>$_POST</code> will return empty. If you use <code>$_GET</code> it will work. I often use <code>$_REQUEST</code> to avoid this issue.</p>\n\n<p>As Pat comments, <code>add_action</code> always returns true. So if you need to return erros to show this in the form, then you should consider sending the form via ajax.</p>\n\n<pre><code>function signup_validate_insert()\n{\n $errors = false;\n if (!empty($_POST['submit_msg'])) {\n // Do your validation\n } else {\n $errors = true;\n }\n\n //If no errors are found, procede with form submition.\n if(!$errors){\n wp_redirect( $location, $status );\n exit;\n } else { \n /*\n If errors are found you have 3 options:\n 1. Store the errors in a db table and retrieve the errors in the page template \n 2. Store the errors in a cookie\n 3. Redirect page to form and put the erros in the URL\n\n */\n }\n}\n</code></pre>\n\n<p>I would however strongly recommend you to submit the for via jQuery and return errors if any. If not, redirect data to the page to ahndle the form submission.</p>\n\n<pre><code>var formData = $('form').serialize()\n\n$.ajax({\n type: \"POST\",\n url: url,\n data: formData ,\n success: success,\n dataType: dataType\n});\n</code></pre>\n"
},
{
"answer_id": 206873,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>actions do not \"return\" values. If you need to do some heavy computation that you want to avoid redoing at a later stage then you should store the value at a global variable (pure global, static or a field in an object depending on your favorite coding style).</p>\n"
}
] |
2015/10/28
|
[
"https://wordpress.stackexchange.com/questions/206862",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82394/"
] |
I have a function which checks if $\_POST is set (a form which submits to the same page). I need to have it initialized before the page is loaded because the function will do a header **redirect** if the validation goes through without errors.
So the function is registered like this:
```
add_action('init', 'signup_validate_insert');
```
And the function itself starts like this:
```
function signup_validate_insert(){
$errors = false;
if (!empty($_POST['submit_msg'])) {
//validation and stuff
}
```
And if there are errors, it returns the errors array:
```
return $errors;
```
When the submit button is pressed, the function registers it as it should, and goes through the validation. I have checked to see that the errors array is being filled in the function. But the variable is not returned! (although I have set "return $errors")
The variable is supposed to be returned to the template, where the errors can be displayed if $errors are not empty.
I have tried switching to `add_filter` instead, with the same result.
So the question is really how to be able to return this variable - hope you can help!
|
actions do not "return" values. If you need to do some heavy computation that you want to avoid redoing at a later stage then you should store the value at a global variable (pure global, static or a field in an object depending on your favorite coding style).
|
206,880 |
<p>Based on <a href="https://docs.woothemes.com/document/adjust-the-quantity-input-values/" rel="nofollow">this snippet</a>, which checks the quantity in cart for MAX value: </p>
<pre><code>add_filter( 'woocommerce_quantity_input_args', 'jk_woocommerce_quantity_input_args', 10, 2 );
function jk_woocommerce_quantity_input_args( $args, $product ) {
$args['max_value'] = 10; // Maximum value
return $args;
}
</code></pre>
<p>I'm trying to add a condition, i.e. if the item is <code>onsale</code> AND equals the value of <code>SESSION</code> variable:</p>
<pre><code>add_filter( 'woocommerce_quantity_input_args', 'jk_woocommerce_quantity_input_args', 10, 2 );
function jk_woocommerce_quantity_input_args( $args, $product ) {
$onsale = $product->is_on_sale();
if ( ( $_SESSION['odertype'] = 'local_delivery' ) && $onsale ) {
$args['max_value'] = 10; // Maximum value
return $args;
}
}
</code></pre>
<p>Unfortunately, it looks like the 'AND' portion of the <code>IF</code> statement is not working, as the filter seems to be applied even if the session variable is NOT set!</p>
|
[
{
"answer_id": 206927,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>SimplePie for a long time is not truly an independent project as it was fully assimilated into wordpress. Not sure that there is any new development for it, but if there is it is unlikely to be any different than what it is at the latest wordpress core.</p>\n"
},
{
"answer_id": 356318,
"author": "Majal",
"author_id": 181015,
"author_profile": "https://wordpress.stackexchange.com/users/181015",
"pm_score": 0,
"selected": false,
"text": "<p>The bug is <a href=\"https://core.trac.wordpress.org/ticket/36669\" rel=\"nofollow noreferrer\">supposed to be resolved</a> in WP 5.4 (March 2020 delivery).</p>\n\n<p>Meanwhile, this plugin may provide a temporary fix: <a href=\"https://github.com/michaeluno/_fix-simplepie-errors\" rel=\"nofollow noreferrer\">https://github.com/michaeluno/_fix-simplepie-errors</a></p>\n"
}
] |
2015/10/28
|
[
"https://wordpress.stackexchange.com/questions/206880",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82637/"
] |
Based on [this snippet](https://docs.woothemes.com/document/adjust-the-quantity-input-values/), which checks the quantity in cart for MAX value:
```
add_filter( 'woocommerce_quantity_input_args', 'jk_woocommerce_quantity_input_args', 10, 2 );
function jk_woocommerce_quantity_input_args( $args, $product ) {
$args['max_value'] = 10; // Maximum value
return $args;
}
```
I'm trying to add a condition, i.e. if the item is `onsale` AND equals the value of `SESSION` variable:
```
add_filter( 'woocommerce_quantity_input_args', 'jk_woocommerce_quantity_input_args', 10, 2 );
function jk_woocommerce_quantity_input_args( $args, $product ) {
$onsale = $product->is_on_sale();
if ( ( $_SESSION['odertype'] = 'local_delivery' ) && $onsale ) {
$args['max_value'] = 10; // Maximum value
return $args;
}
}
```
Unfortunately, it looks like the 'AND' portion of the `IF` statement is not working, as the filter seems to be applied even if the session variable is NOT set!
|
SimplePie for a long time is not truly an independent project as it was fully assimilated into wordpress. Not sure that there is any new development for it, but if there is it is unlikely to be any different than what it is at the latest wordpress core.
|
206,886 |
<p>I want to load products deatails on my custom page.Is there any way that i can use the <code>url key</code> like <code>http://localhost/mysite/product/samsung-1</code>.In this url <code>samsung-1</code> is the key for that product.I want to use this and get product details like name,description and attributes.Can i do this using <code>url key</code> or i have to use id for this.thanks
I tried this code but this uses id :</p>
<pre><code><?php $post = get_post('5653'); //assuming $id has been initialized
echo "<pre/>";
print_r($post);
wp_reset_postdata();?>
</code></pre>
|
[
{
"answer_id": 206890,
"author": "M-R",
"author_id": 17061,
"author_profile": "https://wordpress.stackexchange.com/users/17061",
"pm_score": 2,
"selected": false,
"text": "<p>You can use following function</p>\n\n<pre><code>/**\n* Retrieve a product given its slug.\n*/\n\nfunction get_product_by_slug($page_slug, $output = OBJECT) {\n global $wpdb;\n $product = $wpdb->get_var( $wpdb->prepare( \"SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s\", $page_slug, 'product'));\n if ( $product )\n return get_post($product, $output);\n\n return null;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>$product = get_product_by_slug('samsung-1');\n</code></pre>\n\n<p>Its not tested though</p>\n"
},
{
"answer_id": 206893,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 4,
"selected": true,
"text": "<p>You simply can use the existing function <a href=\"https://codex.wordpress.org/Function_Reference/get_page_by_path\" rel=\"noreferrer\"><code>get_page_by_path()</code></a> for this, which has a third parameter <code>$post_type</code> you can specify. In your case a post from the custom post type <code>product</code> is what you want.</p>\n\n<p>Basic example:</p>\n\n<pre><code>$product_obj = get_page_by_path( $slug, OBJECT, 'product' );\n</code></pre>\n"
}
] |
2015/10/28
|
[
"https://wordpress.stackexchange.com/questions/206886",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45724/"
] |
I want to load products deatails on my custom page.Is there any way that i can use the `url key` like `http://localhost/mysite/product/samsung-1`.In this url `samsung-1` is the key for that product.I want to use this and get product details like name,description and attributes.Can i do this using `url key` or i have to use id for this.thanks
I tried this code but this uses id :
```
<?php $post = get_post('5653'); //assuming $id has been initialized
echo "<pre/>";
print_r($post);
wp_reset_postdata();?>
```
|
You simply can use the existing function [`get_page_by_path()`](https://codex.wordpress.org/Function_Reference/get_page_by_path) for this, which has a third parameter `$post_type` you can specify. In your case a post from the custom post type `product` is what you want.
Basic example:
```
$product_obj = get_page_by_path( $slug, OBJECT, 'product' );
```
|
206,894 |
<p>I am trying to get a list of my Wordpress categories to display on a Page, but haven't cracked this yet. </p>
<p>So far, I have been able to create a <strong>custom category page</strong> (category-categoryname.php), to display a list of Page Titles associated with a single category. The code I have used for this includes the following Loop:</p>
<pre><code>while ( have_posts() ) : the_post(); ?>
<h4><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h4>
</code></pre>
<p>However, I am now trying to display a list of Category titles on a normal WP Page, using the plugin "Post Snippets" to insert the PHP.</p>
<p><strong>Q1:</strong> How do I change The Loop to display all Category titles, instead of Pages associated with a single category?</p>
<p><strong>Q2:</strong> Is there anything else I need to add, like some code to functions.php etc?</p>
<p><strong>Q3:</strong> Would it be easier to create a custom page template, instead of pasting into a regular page?</p>
<p>Note, I am not trying to filter out any categories from the list, like sub-categories or categories without associated pages/posts etc. Although filtering out 'Uncategorised' would be nice.</p>
<p>Thank you for reading</p>
|
[
{
"answer_id": 206890,
"author": "M-R",
"author_id": 17061,
"author_profile": "https://wordpress.stackexchange.com/users/17061",
"pm_score": 2,
"selected": false,
"text": "<p>You can use following function</p>\n\n<pre><code>/**\n* Retrieve a product given its slug.\n*/\n\nfunction get_product_by_slug($page_slug, $output = OBJECT) {\n global $wpdb;\n $product = $wpdb->get_var( $wpdb->prepare( \"SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s\", $page_slug, 'product'));\n if ( $product )\n return get_post($product, $output);\n\n return null;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>$product = get_product_by_slug('samsung-1');\n</code></pre>\n\n<p>Its not tested though</p>\n"
},
{
"answer_id": 206893,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 4,
"selected": true,
"text": "<p>You simply can use the existing function <a href=\"https://codex.wordpress.org/Function_Reference/get_page_by_path\" rel=\"noreferrer\"><code>get_page_by_path()</code></a> for this, which has a third parameter <code>$post_type</code> you can specify. In your case a post from the custom post type <code>product</code> is what you want.</p>\n\n<p>Basic example:</p>\n\n<pre><code>$product_obj = get_page_by_path( $slug, OBJECT, 'product' );\n</code></pre>\n"
}
] |
2015/10/28
|
[
"https://wordpress.stackexchange.com/questions/206894",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69746/"
] |
I am trying to get a list of my Wordpress categories to display on a Page, but haven't cracked this yet.
So far, I have been able to create a **custom category page** (category-categoryname.php), to display a list of Page Titles associated with a single category. The code I have used for this includes the following Loop:
```
while ( have_posts() ) : the_post(); ?>
<h4><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h4>
```
However, I am now trying to display a list of Category titles on a normal WP Page, using the plugin "Post Snippets" to insert the PHP.
**Q1:** How do I change The Loop to display all Category titles, instead of Pages associated with a single category?
**Q2:** Is there anything else I need to add, like some code to functions.php etc?
**Q3:** Would it be easier to create a custom page template, instead of pasting into a regular page?
Note, I am not trying to filter out any categories from the list, like sub-categories or categories without associated pages/posts etc. Although filtering out 'Uncategorised' would be nice.
Thank you for reading
|
You simply can use the existing function [`get_page_by_path()`](https://codex.wordpress.org/Function_Reference/get_page_by_path) for this, which has a third parameter `$post_type` you can specify. In your case a post from the custom post type `product` is what you want.
Basic example:
```
$product_obj = get_page_by_path( $slug, OBJECT, 'product' );
```
|
206,906 |
<p>Just wanted some advice in relation to adding some custom code to my wordpress site. I am using <code>geoip</code> to check a users country code and redirect them to the relevant site when they land on my homepage.</p>
<p>Currently I include this block of <code>php</code> code at the very top of my themes <code>header.php</code> file. However I'm not sure that is the best way to go about it, would it be better off in the <code>functions.php</code> and if so is there a <code>hook</code> I can use to call this code when the homepage is about to be loaded and redirect accordingly? </p>
<pre><code>$url = $_SERVER['REQUEST_URI'];
require_once("geoip.inc");
$gi = geoip_open(dirname(__FILE__) . "/GeoIP.dat", GEOIP_STANDARD);
$country_code = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);
if ($url === "/") {
//If IE go to /ie
if ($country_code === "IE") {
header("Location: http://www.wpmultisite.com/ie");
die();
}//If GB go to /uk
else if ($country_code === "GB") {
header("Location: http://www.wpmultisite.com/uk");
die();
}
}
</code></pre>
<p>I should point out I'm trying to set up a network of sites using the <code>Wordpress Multisite</code> functionality. </p>
<p>Many thanks in advance for any of your help.</p>
|
[
{
"answer_id": 206898,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>The answer depends on why are you moving the folder.</p>\n\n<p>If you just need to folder to be moved but leave the URLs the same then you will need to adjust yout apache/nginx config files to point to the right directory when serving a request for a url of the type /wp-content/...</p>\n\n<p>If you need to adjust the url as well then you need to also define appropriate <code>WP_CONTENT_URL</code></p>\n"
},
{
"answer_id": 259965,
"author": "Umashankar Chaudhary",
"author_id": 114824,
"author_profile": "https://wordpress.stackexchange.com/users/114824",
"pm_score": 0,
"selected": false,
"text": "<p>Create a folder as blog.</p>\n\n<p>put wp-contant folder in blog folder.</p>\n\n<p>define this line in config.php</p>\n\n<p>/* That's all, stop editing! Happy bloggin.! */</p>\n\n<p>define( 'WP_CONTENT_DIR', dirname(<strong>FILE</strong>) . '/blog/wp-content' );</p>\n"
}
] |
2015/10/28
|
[
"https://wordpress.stackexchange.com/questions/206906",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26255/"
] |
Just wanted some advice in relation to adding some custom code to my wordpress site. I am using `geoip` to check a users country code and redirect them to the relevant site when they land on my homepage.
Currently I include this block of `php` code at the very top of my themes `header.php` file. However I'm not sure that is the best way to go about it, would it be better off in the `functions.php` and if so is there a `hook` I can use to call this code when the homepage is about to be loaded and redirect accordingly?
```
$url = $_SERVER['REQUEST_URI'];
require_once("geoip.inc");
$gi = geoip_open(dirname(__FILE__) . "/GeoIP.dat", GEOIP_STANDARD);
$country_code = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);
if ($url === "/") {
//If IE go to /ie
if ($country_code === "IE") {
header("Location: http://www.wpmultisite.com/ie");
die();
}//If GB go to /uk
else if ($country_code === "GB") {
header("Location: http://www.wpmultisite.com/uk");
die();
}
}
```
I should point out I'm trying to set up a network of sites using the `Wordpress Multisite` functionality.
Many thanks in advance for any of your help.
|
The answer depends on why are you moving the folder.
If you just need to folder to be moved but leave the URLs the same then you will need to adjust yout apache/nginx config files to point to the right directory when serving a request for a url of the type /wp-content/...
If you need to adjust the url as well then you need to also define appropriate `WP_CONTENT_URL`
|
206,907 |
<p>I'm building a multisite in which site admins have no "manage options" capability. The problem is that withut this cap they cannot see the "site identity" tab in the customizer, where they can change the site icon (favicon) as well as the site's name.</p>
<p>Is there a way to change the required capability to show this tab and save its contents? If not, is there a way to display the same fields as in this tab but in a custom tab in the customizer?</p>
<p>Thank you and have a nice day.</p>
|
[
{
"answer_id": 206920,
"author": "Pavel S.",
"author_id": 82344,
"author_profile": "https://wordpress.stackexchange.com/users/82344",
"pm_score": 0,
"selected": false,
"text": "<p>You can remove the <code>title_tagline</code> section from the customizer and add your own section with customs control, which are basicly a copy of \"Site Identity\" piece <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-customize-manager.php#L1730\" rel=\"nofollow\">here</a>.</p>\n\n<p>You will only have to change the capability specified there with one that your administrators have.</p>\n\n<p>You can check out how to use WordPress Customize API Manager in the <a href=\"https://developer.wordpress.org/themes/advanced-topics/customizer-api/\" rel=\"nofollow\">official doc</a>.</p>\n"
},
{
"answer_id": 206951,
"author": "Bryan Willis",
"author_id": 38123,
"author_profile": "https://wordpress.stackexchange.com/users/38123",
"pm_score": 3,
"selected": true,
"text": "<p><strong>This is how I've interpreted from the wordpress <a href=\"https://codex.wordpress.org/Class_Reference/WP_Customize_Manager/get_setting\" rel=\"nofollow\">docs</a> at least. Originally these settings were made with <code>add_setting</code> and it is where the capability was originally set. Fortunately, we can use <code>get_setting</code> to change that value. It seems to work very well for your case.</strong>\n<br></p>\n\n<pre><code>function wpseo_206907_add_back_customizer_controls_for_not_admins( $wp_customize ) {\n $wp_customize->get_setting( 'blogname' )->capability = 'edit_theme_options'; // or edit_posts or whatever capability your site owner has\n}\nadd_action( 'customize_register', 'wpseo_206907_add_back_customizer_controls_for_not_admins', 1000 );\n</code></pre>\n\n<p><br></p>\n\n<hr>\n\n<p><strong>If for some reason they don't have access to the customizer you need to give them the edit_theme_options capability first.</strong></p>\n\n<pre><code>function wpseo_206951_add_capability_for_non_admin() {\n $roleObject = get_role( 'editor' ); // whoever should have access to theme changes\n if (!$roleObject->has_cap( 'edit_theme_options' ) ) {\n $roleObject->add_cap( 'edit_theme_options' );\n }\n}\nadd_action( 'admin_init', 'wpseo_206951_add_capability_for_non_admin');\n</code></pre>\n\n<p><br>\n<strong>This will give them access to the following:</strong><br>\nAppearance > Widgets<br>\nAppearance > Menus<br>\nAppearance > Customize if they are supported by the current theme<br>\nAppearance > Background<br>\nAppearance > Header<br></p>\n\n<p><br>\n<strong>If you'd rather hide these pages all together do this:</strong></p>\n\n<pre><code>function wpseo_206907_remove_by_caps_admin_menu() {\n if ( !current_user_can('manage_options') ) {\n remove_menu_page('themes.php'); // Appearance Menu on Admin\n remove_submenu_page( 'themes.php', 'widgets.php' );\n remove_submenu_page( 'themes.php', 'nav-menus.php' );\n remove_submenu_page( 'themes.php', 'theme-editor.php' );\n }\n}\nadd_action('admin_menu', 'wpseo_206907_remove_by_caps_admin_menu', 999);\n</code></pre>\n\n<p><br>\n<strong>However, if you want them to have access to certain pages like widgets and menus, but not themes then do this instead:</strong></p>\n\n<pre><code>add_action( 'admin_init', 'wpseo_206907_lock_theme' ); \nfunction wpseo_206907_lock_theme() {\n global $submenu, $userdata;\n get_currentuserinfo();\n\n if ( $userdata->ID != 1 ) { \n unset( $submenu['themes.php'][5] );\n unset( $submenu['themes.php'][15] );\n }\n}\n</code></pre>\n\n<p><br>\n<strong>You'd also want to do this then to remove the theme change section section from the customizer:</strong></p>\n\n<pre><code>function wpseo_206951_remove_customizer_controls_all( $wp_customize ) { \n if ( !current_user_can('manage_options') ) {\n\n $wp_customize->remove_section(\"themes\"); // Removes Themes section from backend\n\n // To remove other sections, panels, controls look in html source code in chrome dev tools or firefox or whatever and it will tell you the id and whether it's a section or panel or control. \n //Example below (uncomment to use)\n\n // $wp_customize->remove_section(\"title_tagline\");\n // $wp_customize->remove_panel(\"nav_menus\");\n // $wp_customize->remove_panel(\"widgets\");\n // $wp_customize->remove_section(\"static_front_page\");\n\n }\n}\nadd_action( 'customize_register', 'wpseo_206951_remove_customizer_controls_all', 999 );\n</code></pre>\n"
}
] |
2015/10/28
|
[
"https://wordpress.stackexchange.com/questions/206907",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/7212/"
] |
I'm building a multisite in which site admins have no "manage options" capability. The problem is that withut this cap they cannot see the "site identity" tab in the customizer, where they can change the site icon (favicon) as well as the site's name.
Is there a way to change the required capability to show this tab and save its contents? If not, is there a way to display the same fields as in this tab but in a custom tab in the customizer?
Thank you and have a nice day.
|
**This is how I've interpreted from the wordpress [docs](https://codex.wordpress.org/Class_Reference/WP_Customize_Manager/get_setting) at least. Originally these settings were made with `add_setting` and it is where the capability was originally set. Fortunately, we can use `get_setting` to change that value. It seems to work very well for your case.**
```
function wpseo_206907_add_back_customizer_controls_for_not_admins( $wp_customize ) {
$wp_customize->get_setting( 'blogname' )->capability = 'edit_theme_options'; // or edit_posts or whatever capability your site owner has
}
add_action( 'customize_register', 'wpseo_206907_add_back_customizer_controls_for_not_admins', 1000 );
```
---
**If for some reason they don't have access to the customizer you need to give them the edit\_theme\_options capability first.**
```
function wpseo_206951_add_capability_for_non_admin() {
$roleObject = get_role( 'editor' ); // whoever should have access to theme changes
if (!$roleObject->has_cap( 'edit_theme_options' ) ) {
$roleObject->add_cap( 'edit_theme_options' );
}
}
add_action( 'admin_init', 'wpseo_206951_add_capability_for_non_admin');
```
**This will give them access to the following:**
Appearance > Widgets
Appearance > Menus
Appearance > Customize if they are supported by the current theme
Appearance > Background
Appearance > Header
**If you'd rather hide these pages all together do this:**
```
function wpseo_206907_remove_by_caps_admin_menu() {
if ( !current_user_can('manage_options') ) {
remove_menu_page('themes.php'); // Appearance Menu on Admin
remove_submenu_page( 'themes.php', 'widgets.php' );
remove_submenu_page( 'themes.php', 'nav-menus.php' );
remove_submenu_page( 'themes.php', 'theme-editor.php' );
}
}
add_action('admin_menu', 'wpseo_206907_remove_by_caps_admin_menu', 999);
```
**However, if you want them to have access to certain pages like widgets and menus, but not themes then do this instead:**
```
add_action( 'admin_init', 'wpseo_206907_lock_theme' );
function wpseo_206907_lock_theme() {
global $submenu, $userdata;
get_currentuserinfo();
if ( $userdata->ID != 1 ) {
unset( $submenu['themes.php'][5] );
unset( $submenu['themes.php'][15] );
}
}
```
**You'd also want to do this then to remove the theme change section section from the customizer:**
```
function wpseo_206951_remove_customizer_controls_all( $wp_customize ) {
if ( !current_user_can('manage_options') ) {
$wp_customize->remove_section("themes"); // Removes Themes section from backend
// To remove other sections, panels, controls look in html source code in chrome dev tools or firefox or whatever and it will tell you the id and whether it's a section or panel or control.
//Example below (uncomment to use)
// $wp_customize->remove_section("title_tagline");
// $wp_customize->remove_panel("nav_menus");
// $wp_customize->remove_panel("widgets");
// $wp_customize->remove_section("static_front_page");
}
}
add_action( 'customize_register', 'wpseo_206951_remove_customizer_controls_all', 999 );
```
|
206,916 |
<p>What will be best way to split large database on single site, not multi-site wp installation? <a href="https://wordpress.org/plugins/hyperdb/" rel="nofollow">HyperDB</a> is maybe for this (just, less than 10 webmasters managed to figure out how to install it, according to active installs).</p>
<p>Currently site has about 350k posts, it is on good VPS. Site is running quite fast in fronted, opening pages, browsings... But it slows down at back-end when publishing new posts, every day lots of new posts are added.</p>
<p>Site has this permalink structure:</p>
<p>sitename.com/year/month/day/postid/post-name
Practically just new posts are edited, and once published post are not changed. </p>
<p>Any idea how to speed up database writing, or better, to have published post in one database, and have new database for future posts?</p>
<hr>
<p><strong>Update:</strong></p>
<p><strong>First installation</strong>: Is installation in root of site with new database, without old, published posts, just for future posts. Permalink structure is as it was:</p>
<p>sitename.com/year/month/day/postid/post-name</p>
<p><strong>Second installation:</strong>
Created folder "2015" in root of site and installed WP in that folder with sql database of original WP installation from root, with all posts up to end of September, just permalink are changed to:</p>
<p>sitename.com/month/day/postid/post-name</p>
<p>and it will give the same URL structure as it was (because WP is in sub-folder "2015"):</p>
<p>sitename.com/year/month/day/postid/post-name</p>
<p>This approach is working when I need to split database once per year (for example for year 2014). For every past year I can have one folder named by past year and with WP installation in that folder with database with posts of that past year.</p>
<p>That way when visitor try to open URL for example:</p>
<p>sitename.com/2014/01/01/post-name-here</p>
<p>server will look first in sub-folder /2014/ and there is WP installation which will return that post.</p>
<p><strong>Problem:</strong>
When database is too big for current year I tried to split posts from current year into two databases, one have all published posts from this year up to end of September, and another will have future post.</p>
<p>I have this:</p>
<p>In root of site I have folder "2015" with WP installation with permalink structure:</p>
<p>sitename.com/month/day/postid/post-name</p>
<p>And in root WP installation with permalink structure:</p>
<p>sitename.com/year/month/day/postid/post-name</p>
<p>If I try to open URL:</p>
<p>sitename.com/2015/09/01/post-name-here</p>
<p>server will check in folder "2015" and WP installation from that folder will return post from 1st September, and it works fine.</p>
<p>If I publish new post today in WP installation in root of site it will have URL like this:
sitename.com/2015/10/29/post-name-here</p>
<p>And If I try to open it, server will look in WP installation inside of folder "2015", but that installation have posts just up to end of September, and I get 404. After that server will not look inside WP installation in root of site where that post is.</p>
<p><strong>Question:</strong></p>
<p><strong>How to make server look in WP installation inside sub folder "2015", and if there is no post in that installation to look for that post inside WP installation in root of site?</strong></p>
|
[
{
"answer_id": 206920,
"author": "Pavel S.",
"author_id": 82344,
"author_profile": "https://wordpress.stackexchange.com/users/82344",
"pm_score": 0,
"selected": false,
"text": "<p>You can remove the <code>title_tagline</code> section from the customizer and add your own section with customs control, which are basicly a copy of \"Site Identity\" piece <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-customize-manager.php#L1730\" rel=\"nofollow\">here</a>.</p>\n\n<p>You will only have to change the capability specified there with one that your administrators have.</p>\n\n<p>You can check out how to use WordPress Customize API Manager in the <a href=\"https://developer.wordpress.org/themes/advanced-topics/customizer-api/\" rel=\"nofollow\">official doc</a>.</p>\n"
},
{
"answer_id": 206951,
"author": "Bryan Willis",
"author_id": 38123,
"author_profile": "https://wordpress.stackexchange.com/users/38123",
"pm_score": 3,
"selected": true,
"text": "<p><strong>This is how I've interpreted from the wordpress <a href=\"https://codex.wordpress.org/Class_Reference/WP_Customize_Manager/get_setting\" rel=\"nofollow\">docs</a> at least. Originally these settings were made with <code>add_setting</code> and it is where the capability was originally set. Fortunately, we can use <code>get_setting</code> to change that value. It seems to work very well for your case.</strong>\n<br></p>\n\n<pre><code>function wpseo_206907_add_back_customizer_controls_for_not_admins( $wp_customize ) {\n $wp_customize->get_setting( 'blogname' )->capability = 'edit_theme_options'; // or edit_posts or whatever capability your site owner has\n}\nadd_action( 'customize_register', 'wpseo_206907_add_back_customizer_controls_for_not_admins', 1000 );\n</code></pre>\n\n<p><br></p>\n\n<hr>\n\n<p><strong>If for some reason they don't have access to the customizer you need to give them the edit_theme_options capability first.</strong></p>\n\n<pre><code>function wpseo_206951_add_capability_for_non_admin() {\n $roleObject = get_role( 'editor' ); // whoever should have access to theme changes\n if (!$roleObject->has_cap( 'edit_theme_options' ) ) {\n $roleObject->add_cap( 'edit_theme_options' );\n }\n}\nadd_action( 'admin_init', 'wpseo_206951_add_capability_for_non_admin');\n</code></pre>\n\n<p><br>\n<strong>This will give them access to the following:</strong><br>\nAppearance > Widgets<br>\nAppearance > Menus<br>\nAppearance > Customize if they are supported by the current theme<br>\nAppearance > Background<br>\nAppearance > Header<br></p>\n\n<p><br>\n<strong>If you'd rather hide these pages all together do this:</strong></p>\n\n<pre><code>function wpseo_206907_remove_by_caps_admin_menu() {\n if ( !current_user_can('manage_options') ) {\n remove_menu_page('themes.php'); // Appearance Menu on Admin\n remove_submenu_page( 'themes.php', 'widgets.php' );\n remove_submenu_page( 'themes.php', 'nav-menus.php' );\n remove_submenu_page( 'themes.php', 'theme-editor.php' );\n }\n}\nadd_action('admin_menu', 'wpseo_206907_remove_by_caps_admin_menu', 999);\n</code></pre>\n\n<p><br>\n<strong>However, if you want them to have access to certain pages like widgets and menus, but not themes then do this instead:</strong></p>\n\n<pre><code>add_action( 'admin_init', 'wpseo_206907_lock_theme' ); \nfunction wpseo_206907_lock_theme() {\n global $submenu, $userdata;\n get_currentuserinfo();\n\n if ( $userdata->ID != 1 ) { \n unset( $submenu['themes.php'][5] );\n unset( $submenu['themes.php'][15] );\n }\n}\n</code></pre>\n\n<p><br>\n<strong>You'd also want to do this then to remove the theme change section section from the customizer:</strong></p>\n\n<pre><code>function wpseo_206951_remove_customizer_controls_all( $wp_customize ) { \n if ( !current_user_can('manage_options') ) {\n\n $wp_customize->remove_section(\"themes\"); // Removes Themes section from backend\n\n // To remove other sections, panels, controls look in html source code in chrome dev tools or firefox or whatever and it will tell you the id and whether it's a section or panel or control. \n //Example below (uncomment to use)\n\n // $wp_customize->remove_section(\"title_tagline\");\n // $wp_customize->remove_panel(\"nav_menus\");\n // $wp_customize->remove_panel(\"widgets\");\n // $wp_customize->remove_section(\"static_front_page\");\n\n }\n}\nadd_action( 'customize_register', 'wpseo_206951_remove_customizer_controls_all', 999 );\n</code></pre>\n"
}
] |
2015/10/28
|
[
"https://wordpress.stackexchange.com/questions/206916",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25053/"
] |
What will be best way to split large database on single site, not multi-site wp installation? [HyperDB](https://wordpress.org/plugins/hyperdb/) is maybe for this (just, less than 10 webmasters managed to figure out how to install it, according to active installs).
Currently site has about 350k posts, it is on good VPS. Site is running quite fast in fronted, opening pages, browsings... But it slows down at back-end when publishing new posts, every day lots of new posts are added.
Site has this permalink structure:
sitename.com/year/month/day/postid/post-name
Practically just new posts are edited, and once published post are not changed.
Any idea how to speed up database writing, or better, to have published post in one database, and have new database for future posts?
---
**Update:**
**First installation**: Is installation in root of site with new database, without old, published posts, just for future posts. Permalink structure is as it was:
sitename.com/year/month/day/postid/post-name
**Second installation:**
Created folder "2015" in root of site and installed WP in that folder with sql database of original WP installation from root, with all posts up to end of September, just permalink are changed to:
sitename.com/month/day/postid/post-name
and it will give the same URL structure as it was (because WP is in sub-folder "2015"):
sitename.com/year/month/day/postid/post-name
This approach is working when I need to split database once per year (for example for year 2014). For every past year I can have one folder named by past year and with WP installation in that folder with database with posts of that past year.
That way when visitor try to open URL for example:
sitename.com/2014/01/01/post-name-here
server will look first in sub-folder /2014/ and there is WP installation which will return that post.
**Problem:**
When database is too big for current year I tried to split posts from current year into two databases, one have all published posts from this year up to end of September, and another will have future post.
I have this:
In root of site I have folder "2015" with WP installation with permalink structure:
sitename.com/month/day/postid/post-name
And in root WP installation with permalink structure:
sitename.com/year/month/day/postid/post-name
If I try to open URL:
sitename.com/2015/09/01/post-name-here
server will check in folder "2015" and WP installation from that folder will return post from 1st September, and it works fine.
If I publish new post today in WP installation in root of site it will have URL like this:
sitename.com/2015/10/29/post-name-here
And If I try to open it, server will look in WP installation inside of folder "2015", but that installation have posts just up to end of September, and I get 404. After that server will not look inside WP installation in root of site where that post is.
**Question:**
**How to make server look in WP installation inside sub folder "2015", and if there is no post in that installation to look for that post inside WP installation in root of site?**
|
**This is how I've interpreted from the wordpress [docs](https://codex.wordpress.org/Class_Reference/WP_Customize_Manager/get_setting) at least. Originally these settings were made with `add_setting` and it is where the capability was originally set. Fortunately, we can use `get_setting` to change that value. It seems to work very well for your case.**
```
function wpseo_206907_add_back_customizer_controls_for_not_admins( $wp_customize ) {
$wp_customize->get_setting( 'blogname' )->capability = 'edit_theme_options'; // or edit_posts or whatever capability your site owner has
}
add_action( 'customize_register', 'wpseo_206907_add_back_customizer_controls_for_not_admins', 1000 );
```
---
**If for some reason they don't have access to the customizer you need to give them the edit\_theme\_options capability first.**
```
function wpseo_206951_add_capability_for_non_admin() {
$roleObject = get_role( 'editor' ); // whoever should have access to theme changes
if (!$roleObject->has_cap( 'edit_theme_options' ) ) {
$roleObject->add_cap( 'edit_theme_options' );
}
}
add_action( 'admin_init', 'wpseo_206951_add_capability_for_non_admin');
```
**This will give them access to the following:**
Appearance > Widgets
Appearance > Menus
Appearance > Customize if they are supported by the current theme
Appearance > Background
Appearance > Header
**If you'd rather hide these pages all together do this:**
```
function wpseo_206907_remove_by_caps_admin_menu() {
if ( !current_user_can('manage_options') ) {
remove_menu_page('themes.php'); // Appearance Menu on Admin
remove_submenu_page( 'themes.php', 'widgets.php' );
remove_submenu_page( 'themes.php', 'nav-menus.php' );
remove_submenu_page( 'themes.php', 'theme-editor.php' );
}
}
add_action('admin_menu', 'wpseo_206907_remove_by_caps_admin_menu', 999);
```
**However, if you want them to have access to certain pages like widgets and menus, but not themes then do this instead:**
```
add_action( 'admin_init', 'wpseo_206907_lock_theme' );
function wpseo_206907_lock_theme() {
global $submenu, $userdata;
get_currentuserinfo();
if ( $userdata->ID != 1 ) {
unset( $submenu['themes.php'][5] );
unset( $submenu['themes.php'][15] );
}
}
```
**You'd also want to do this then to remove the theme change section section from the customizer:**
```
function wpseo_206951_remove_customizer_controls_all( $wp_customize ) {
if ( !current_user_can('manage_options') ) {
$wp_customize->remove_section("themes"); // Removes Themes section from backend
// To remove other sections, panels, controls look in html source code in chrome dev tools or firefox or whatever and it will tell you the id and whether it's a section or panel or control.
//Example below (uncomment to use)
// $wp_customize->remove_section("title_tagline");
// $wp_customize->remove_panel("nav_menus");
// $wp_customize->remove_panel("widgets");
// $wp_customize->remove_section("static_front_page");
}
}
add_action( 'customize_register', 'wpseo_206951_remove_customizer_controls_all', 999 );
```
|
206,957 |
<p>I have some js scripts that are working on my site but I have found that some of the images are not showing up. I only have this issue with WordPress. So I have a pause button that shows as it's supposed to. When you press the button, it pauses the script as it's supposed to. When this happens, a new image is added to replace the pause button. The image gets inserted into the page. So it looks like this when it's playing</p>
<pre><code> <img id="pauseplay" src="http://www.example.com/wp-content/themes/theme/images/pause.png" alt="">
</code></pre>
<p>When I press the pause button, it changes to this</p>
<pre><code> <img id="pauseplay" src="images/play.png" alt="">
</code></pre>
<p>obviously this is a problem with absolute to relative links but I don't know how to fix it.
Why don't relative links work in WordPress?</p>
|
[
{
"answer_id": 206983,
"author": "Tobias Beuving",
"author_id": 2690,
"author_profile": "https://wordpress.stackexchange.com/users/2690",
"pm_score": 0,
"selected": false,
"text": "<p>try a backslash '/' in front of 'images/play.png'</p>\n\n<p>so the url will look like this: '/images/play.png'</p>\n\n<p>(assuming your images directory is in the root of your site)</p>\n"
},
{
"answer_id": 206987,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Relative URLs work nicely in wordpress, which is the reason for your failures. In general never use relative URLs for resources as they will most likely fail when a site is using \"pretty permalinks\".</p>\n\n<p>Best thing for what you are doing is to \"group\" the graphical resources and styling in a CSS (in which resources are relative to the CSS file and not the HTML URL). </p>\n\n<p>The JS alternative is to store the root of the site/theme/plugin in a JS variable and use it to construct the URL. Followin code is to take site root into consideration, but you most likely will want theme or plugin root.</p>\n\n<pre><code><script>\n var homeurl = '<?php echo home_url()?>';\n.....\n pauseImage = homeurl+\"images/play.png\"; // url to your play image\n</script>\n</code></pre>\n"
}
] |
2015/10/29
|
[
"https://wordpress.stackexchange.com/questions/206957",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14761/"
] |
I have some js scripts that are working on my site but I have found that some of the images are not showing up. I only have this issue with WordPress. So I have a pause button that shows as it's supposed to. When you press the button, it pauses the script as it's supposed to. When this happens, a new image is added to replace the pause button. The image gets inserted into the page. So it looks like this when it's playing
```
<img id="pauseplay" src="http://www.example.com/wp-content/themes/theme/images/pause.png" alt="">
```
When I press the pause button, it changes to this
```
<img id="pauseplay" src="images/play.png" alt="">
```
obviously this is a problem with absolute to relative links but I don't know how to fix it.
Why don't relative links work in WordPress?
|
Relative URLs work nicely in wordpress, which is the reason for your failures. In general never use relative URLs for resources as they will most likely fail when a site is using "pretty permalinks".
Best thing for what you are doing is to "group" the graphical resources and styling in a CSS (in which resources are relative to the CSS file and not the HTML URL).
The JS alternative is to store the root of the site/theme/plugin in a JS variable and use it to construct the URL. Followin code is to take site root into consideration, but you most likely will want theme or plugin root.
```
<script>
var homeurl = '<?php echo home_url()?>';
.....
pauseImage = homeurl+"images/play.png"; // url to your play image
</script>
```
|
206,959 |
<p>My goal is to have this link structure:</p>
<p>mypage.com/item/subitem/code</p>
<p>Code are 6 random letters and numbers.</p>
<p>I tried with having category and subcategory, but I dislike that because then i have to create post for every code that i have, and there are lots of it.</p>
<p>What I want to is to have a template for page item/subitem/code and just take code as query (similar to ?code) but I cannot change this structure since it's about qr codes and they cannot be changed.</p>
<p>Is this somehow possible?</p>
|
[
{
"answer_id": 206983,
"author": "Tobias Beuving",
"author_id": 2690,
"author_profile": "https://wordpress.stackexchange.com/users/2690",
"pm_score": 0,
"selected": false,
"text": "<p>try a backslash '/' in front of 'images/play.png'</p>\n\n<p>so the url will look like this: '/images/play.png'</p>\n\n<p>(assuming your images directory is in the root of your site)</p>\n"
},
{
"answer_id": 206987,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Relative URLs work nicely in wordpress, which is the reason for your failures. In general never use relative URLs for resources as they will most likely fail when a site is using \"pretty permalinks\".</p>\n\n<p>Best thing for what you are doing is to \"group\" the graphical resources and styling in a CSS (in which resources are relative to the CSS file and not the HTML URL). </p>\n\n<p>The JS alternative is to store the root of the site/theme/plugin in a JS variable and use it to construct the URL. Followin code is to take site root into consideration, but you most likely will want theme or plugin root.</p>\n\n<pre><code><script>\n var homeurl = '<?php echo home_url()?>';\n.....\n pauseImage = homeurl+\"images/play.png\"; // url to your play image\n</script>\n</code></pre>\n"
}
] |
2015/10/29
|
[
"https://wordpress.stackexchange.com/questions/206959",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82670/"
] |
My goal is to have this link structure:
mypage.com/item/subitem/code
Code are 6 random letters and numbers.
I tried with having category and subcategory, but I dislike that because then i have to create post for every code that i have, and there are lots of it.
What I want to is to have a template for page item/subitem/code and just take code as query (similar to ?code) but I cannot change this structure since it's about qr codes and they cannot be changed.
Is this somehow possible?
|
Relative URLs work nicely in wordpress, which is the reason for your failures. In general never use relative URLs for resources as they will most likely fail when a site is using "pretty permalinks".
Best thing for what you are doing is to "group" the graphical resources and styling in a CSS (in which resources are relative to the CSS file and not the HTML URL).
The JS alternative is to store the root of the site/theme/plugin in a JS variable and use it to construct the URL. Followin code is to take site root into consideration, but you most likely will want theme or plugin root.
```
<script>
var homeurl = '<?php echo home_url()?>';
.....
pauseImage = homeurl+"images/play.png"; // url to your play image
</script>
```
|
206,961 |
<p>I have this code in <code>functions.php</code> that organize media upload according to its Custom Post Type (CPT).</p>
<p>So all images uploaded to a "Product" CPT will be inside <code>wp-content/uploads/product</code> directory.</p>
<pre><code>add_filter("upload_dir", function ($args) {
$id = (isset($_REQUEST["post_id"]) ? $_REQUEST["post_id"] : "");
if($id) {
$newdir = "/" . get_post_type($id);
// remove default dir
$args["path"] = str_replace( $args["subdir"], "", $args["path"]);
$args["url"] = str_replace( $args["subdir"], "", $args["url"]);
// assign new dir
$args["subdir"] = $newdir;
$args["path"] .= $newdir;
$args["url"] .= $newdir;
return $args;
}
});
</code></pre>
<p>It works well, except when I delete the media, the file is still there (the database entry is deleted just fine).</p>
<p>I figured I need to <strong>filter the media deletion</strong> too, but can't seem to find the right way. Have anyone successfully set this up?</p>
<p>Thanks</p>
<p><strong>EDIT</strong></p>
<p>I tried adding conditional to use default folder when the post type is <code>post</code>.</p>
<pre><code>if(get_post_type($id) === "post") {
return $args;
} else {
...
}
</code></pre>
<p>Deleting a Post's media also won't delete the file.</p>
|
[
{
"answer_id": 207603,
"author": "Claudio Rimann",
"author_id": 66433,
"author_profile": "https://wordpress.stackexchange.com/users/66433",
"pm_score": 1,
"selected": false,
"text": "<p>We did something quite similar in our plugin recently.\nHere's how we handle media deletions only when one of <em>our</em> posts is being deleted.</p>\n\n<pre>\n/**\n * Delete all attached media when a product is deleted\n */\nfunction product_delete_attached_media( $post_id ) {\n\n // If it's not a product being deleted, we don't want to do anything\n if ( 'product' != get_post_type( $post_id ) )\n return;\n\n // Setup the arguments for a custom Query\n $args = array(\n 'post_type' => 'attachment', // We want attachments...\n 'posts_per_page' => -1, // ... all of them ...\n 'post_status' => 'any', // ... no matter if public, in trash etc. ...\n 'post_parent' => $post_id // ... that are a child of the product being deleted here!\n );\n\n // Make acustom query with those arguments to get those attachments\n $attachments = new WP_Query( $args );\n\n // Loop through each one of them and delete them\n foreach ( $attachments->posts as $attachment ) {\n if ( false === wp_delete_attachment( $attachment->ID, true ) ) {\n // In here you could output or log something if anything went wrong\n }\n }\n}\n\n// We add this function to the \"before_delete_post\" hook\n// which runs before each deletion of a post\nadd_action( 'before_delete_post', 'product_delete_attached_media' );\n</pre>\n\n<p>The comments should explain what's going on quite well.\nwp_delete_attachment() function takes care of the deletion of the media files and should successfully delete the files as well as the entries in the database.</p>\n\n<p>The only thing we had to do on top of that was to remove the whole custom folder structure if our plugin get's uninstalled.</p>\n\n<p>Also, i'm pretty sure the WP_Query could be optimized as it could potentially get slow if you have a ton of posts and images.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 211025,
"author": "hrsetyono",
"author_id": 33361,
"author_profile": "https://wordpress.stackexchange.com/users/33361",
"pm_score": 3,
"selected": true,
"text": "<p>A small mistake, the <code>return</code> should be outside <code>if</code></p>\n\n<pre><code>add_filter(\"upload_dir\", function ($args) {\n $id = (isset($_REQUEST[\"post_id\"]) ? $_REQUEST[\"post_id\"] : \"\");\n\n if($id) {\n $newdir = \"/\" . get_post_type($id);\n ...\n }\n\n return $args;\n});\n</code></pre>\n"
}
] |
2015/10/29
|
[
"https://wordpress.stackexchange.com/questions/206961",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33361/"
] |
I have this code in `functions.php` that organize media upload according to its Custom Post Type (CPT).
So all images uploaded to a "Product" CPT will be inside `wp-content/uploads/product` directory.
```
add_filter("upload_dir", function ($args) {
$id = (isset($_REQUEST["post_id"]) ? $_REQUEST["post_id"] : "");
if($id) {
$newdir = "/" . get_post_type($id);
// remove default dir
$args["path"] = str_replace( $args["subdir"], "", $args["path"]);
$args["url"] = str_replace( $args["subdir"], "", $args["url"]);
// assign new dir
$args["subdir"] = $newdir;
$args["path"] .= $newdir;
$args["url"] .= $newdir;
return $args;
}
});
```
It works well, except when I delete the media, the file is still there (the database entry is deleted just fine).
I figured I need to **filter the media deletion** too, but can't seem to find the right way. Have anyone successfully set this up?
Thanks
**EDIT**
I tried adding conditional to use default folder when the post type is `post`.
```
if(get_post_type($id) === "post") {
return $args;
} else {
...
}
```
Deleting a Post's media also won't delete the file.
|
A small mistake, the `return` should be outside `if`
```
add_filter("upload_dir", function ($args) {
$id = (isset($_REQUEST["post_id"]) ? $_REQUEST["post_id"] : "");
if($id) {
$newdir = "/" . get_post_type($id);
...
}
return $args;
});
```
|
207,062 |
<p>In the checkout page, there is a review order table on the bottom. I want to remove the order review in checkout page. What is the remove action ?</p>
|
[
{
"answer_id": 207200,
"author": "Rishabh",
"author_id": 81621,
"author_profile": "https://wordpress.stackexchange.com/users/81621",
"pm_score": 1,
"selected": true,
"text": "<p>Just add following code into your funtions.php</p>\n\n<pre><code>add_filter( βwoocommerce_product_tabsβ, βsb_woo_remove_reviews_tabβ, 98);\n\nfunction sb_woo_remove_reviews_tab($tabs) { \nunset($tabs[βreviewsβ]);\nreturn $tabs;\n}\n</code></pre>\n"
},
{
"answer_id": 278477,
"author": "J.D.",
"author_id": 27757,
"author_profile": "https://wordpress.stackexchange.com/users/27757",
"pm_score": 3,
"selected": false,
"text": "<p>You can remove the order summary table like this:</p>\n\n<pre><code>remove_action( 'woocommerce_checkout_order_review', 'woocommerce_order_review', 10 );\n</code></pre>\n\n<p>You could also copy the <code>checkout/review-order.php</code> template to your child theme, and modify it as desired.</p>\n"
}
] |
2015/10/29
|
[
"https://wordpress.stackexchange.com/questions/207062",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82041/"
] |
In the checkout page, there is a review order table on the bottom. I want to remove the order review in checkout page. What is the remove action ?
|
Just add following code into your funtions.php
```
add_filter( βwoocommerce_product_tabsβ, βsb_woo_remove_reviews_tabβ, 98);
function sb_woo_remove_reviews_tab($tabs) {
unset($tabs[βreviewsβ]);
return $tabs;
}
```
|
207,063 |
<p>I want my cart page to show up on my checkout page. And I want to remove the order review from checkout page. so my cart page will show on the top.</p>
|
[
{
"answer_id": 207068,
"author": "Scriptonomy",
"author_id": 82166,
"author_profile": "https://wordpress.stackexchange.com/users/82166",
"pm_score": 0,
"selected": false,
"text": "<p>I will give you the solution to the first part of your question:</p>\n\n<ul>\n<li>Goto WooCommerce Settings->Checkout</li>\n<li>Under Checkout Pages section set Cart Page dropdown to Checkout</li>\n<li>Now anytime shopper hits the cart button they go straight to checkout</li>\n</ul>\n"
},
{
"answer_id": 207413,
"author": "Rishabh",
"author_id": 81621,
"author_profile": "https://wordpress.stackexchange.com/users/81621",
"pm_score": 3,
"selected": true,
"text": "<pre>To remove order review from checkout page...</pre>\n\n<p>In your plugin folder Go To woocommerce->includes->wc-template-functions.php Now press ctrl+f and write woocommerce_order_review and press enter. You will find a function of the same name. Just remove its body(portion that comes under{}) And its done.\n<pre>To show cart page and checkout page on sigle custom page</pre> you can use shortcode <em>[woocommerce_cart]</em> for cart and <em>[woocommerce_checkout]</em> for checkout on a custom page.Use both shortcode on a single page that might do the trick.</p>\n"
}
] |
2015/10/29
|
[
"https://wordpress.stackexchange.com/questions/207063",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82041/"
] |
I want my cart page to show up on my checkout page. And I want to remove the order review from checkout page. so my cart page will show on the top.
|
```
To remove order review from checkout page...
```
In your plugin folder Go To woocommerce->includes->wc-template-functions.php Now press ctrl+f and write woocommerce\_order\_review and press enter. You will find a function of the same name. Just remove its body(portion that comes under{}) And its done.
```
To show cart page and checkout page on sigle custom page
```
you can use shortcode *[woocommerce\_cart]* for cart and *[woocommerce\_checkout]* for checkout on a custom page.Use both shortcode on a single page that might do the trick.
|
207,131 |
<p>I'm using WooCommerce.</p>
<p>When users go to the lost-password page, type in an email address and press "Reset password", the page just reloads. I'm not sure what wordpress normally does, but I would expect it to show a "email has been sent..." page or text.</p>
<p>The e-mail itself is sent just fine.</p>
<p>What could be wrong?</p>
<p>Similar, when the user creates a new password (by following the e-mail link), and click on "save password" the next page is the lost-password page again! That's a bit confusing.</p>
|
[
{
"answer_id": 210911,
"author": "szabesz",
"author_id": 84818,
"author_profile": "https://wordpress.stackexchange.com/users/84818",
"pm_score": 0,
"selected": false,
"text": "<p>This is the solution I came up with: we can override the WooCommerce template file and change it. I do not like overriding template files, because in the future the WooCommerce template might change and we have to copy it again and apply the changes to the overriding template anyway, but I could not find an easier way to do it.</p>\n\n<p>From the WooCommerce plugin directory copy templates/myaccount/form-lost-password.php to woocommerce/myaccount/ into your (child) theme directory. (This is the way to override the standard WC template files)</p>\n\n<p>Apply the following changes (that is: add the lines ending in \"//added by Szabesz ?>\" to the copy of the template file):</p>\n\n<pre><code><?php wc_print_notices(); ?>\n<?php $on_result_page = isset($_POST['wc_reset_password']) && $_POST['wc_reset_password'] == \"true\"; //added by Szabesz ?>\n<?php $on_reset_true_page = isset($_GET['reset']) && $_GET['reset'] == \"true\"; //added by Szabesz ?>\n<form method=\"post\" class=\"lost_reset_password\">\n\n <?php if( 'lost_password' == $args['form'] ) : ?>\n <?php if( !$on_result_page && !$on_reset_true_page ) : //added by Szabesz ?>\n <p><?php echo apply_filters( 'woocommerce_lost_password_message', __( 'Lost your password? Please enter your username or email address. You will receive a link to create a new password via email.', 'woocommerce' ) ); ?></p>\n\n <p class=\"form-row form-row-first\"><label for=\"user_login\"><?php _e( 'Username or email', 'woocommerce' ); ?></label> <input class=\"input-text\" type=\"text\" name=\"user_login\" id=\"user_login\" /></p>\n <?php else : //added by Szabesz ?>\n <?php if ( !$on_reset_true_page ) : //added by Szabesz ?>\n If you want to use the form again, <a href=\"<?php echo esc_attr(wc_get_endpoint_url( 'lost-password', '', wc_get_page_permalink('myaccount') ) ); ?>\">please click here.</a><?php //added by Szabesz ?>\n <?php endif; //added by Szabesz ?>\n <?php endif; //added by Szabesz ?>\n <?php else : ?>\n\n <p><?php echo apply_filters( 'woocommerce_reset_password_message', __( 'Enter a new password below.', 'woocommerce') ); ?></p>\n\n <p class=\"form-row form-row-first\">\n <label for=\"password_1\"><?php _e( 'New password', 'woocommerce' ); ?> <span class=\"required\">*</span></label>\n <input type=\"password\" class=\"input-text\" name=\"password_1\" id=\"password_1\" />\n </p>\n <p class=\"form-row form-row-last\">\n <label for=\"password_2\"><?php _e( 'Re-enter new password', 'woocommerce' ); ?> <span class=\"required\">*</span></label>\n <input type=\"password\" class=\"input-text\" name=\"password_2\" id=\"password_2\" />\n </p>\n\n <input type=\"hidden\" name=\"reset_key\" value=\"<?php echo isset( $args['key'] ) ? $args['key'] : ''; ?>\" />\n <input type=\"hidden\" name=\"reset_login\" value=\"<?php echo isset( $args['login'] ) ? $args['login'] : ''; ?>\" />\n\n <?php endif; ?>\n\n <div class=\"clear\"></div>\n\n <?php do_action( 'woocommerce_lostpassword_form' ); ?>\n <?php if( $args['form'] == 'lost_password' && !$on_result_page && !$on_reset_true_page || $args['form'] == \"reset_password\" ) : //added by Szabesz ?>\n <p class=\"form-row\">\n <input type=\"hidden\" name=\"wc_reset_password\" value=\"true\" />\n <input type=\"submit\" class=\"button\" value=\"<?php echo 'lost_password' == $args['form'] ? __( 'Reset Password', 'woocommerce' ) : __( 'Save', 'woocommerce' ); ?>\" />\n </p>\n\n <?php wp_nonce_field( $args['form'] ); ?>\n <?php endif; //added by Szabesz ?>\n</form>\n</code></pre>\n\n<p>By using these if statements we check the different states of the lost-password page and change it accordingly.</p>\n\n<p>I expect the WooTheme devs to change this template in the future, since the default behavior is really confusing and I wonder why it is implemented in this way in the first place.</p>\n"
},
{
"answer_id": 211016,
"author": "Dennis",
"author_id": 82046,
"author_profile": "https://wordpress.stackexchange.com/users/82046",
"pm_score": 1,
"selected": false,
"text": "<p>I just found another solution to my problem. The problem was that the messages just wasn't displayed properly. By adding this code to my custom CSS (under \"Appearance\"), the messages are now shown again:</p>\n\n<pre><code>.page-id-1154 .woocommerce-message, .page-id-10 .woocommerce-message { \n display: block !important; \n}\n</code></pre>\n"
}
] |
2015/10/30
|
[
"https://wordpress.stackexchange.com/questions/207131",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82046/"
] |
I'm using WooCommerce.
When users go to the lost-password page, type in an email address and press "Reset password", the page just reloads. I'm not sure what wordpress normally does, but I would expect it to show a "email has been sent..." page or text.
The e-mail itself is sent just fine.
What could be wrong?
Similar, when the user creates a new password (by following the e-mail link), and click on "save password" the next page is the lost-password page again! That's a bit confusing.
|
I just found another solution to my problem. The problem was that the messages just wasn't displayed properly. By adding this code to my custom CSS (under "Appearance"), the messages are now shown again:
```
.page-id-1154 .woocommerce-message, .page-id-10 .woocommerce-message {
display: block !important;
}
```
|
207,134 |
<p>I am creating a like system in PHP . My code looks like this .</p>
<pre><code><?php
class Like_System {
private $userid;
private $postid;
private $user_ko_like_count;
private $post_ko_like_count;
private $user_ko_dislike_count;
private $post_ko_dislike_count;
private $user_ip;
public function __construct(){
}
public function our_ajax_script(){
wp_enqueue_script( 'sb_like_post', get_template_directory_uri().'/data/js/post-like.min.js', false, '1.0', 1 );
wp_localize_script( 'sb_like_post', 'ajax_var', array(
'url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'like_system' )
)
);
}
public function load_our_ajax_script(){
add_action( 'init', array($this,"our_ajax_script") );
add_action( 'wp_ajax_nopriv_like_system',array($this,"like_dislike_kernal"));
add_action( 'wp_ajax_like_system',array($this,"like_dislike_kernal"));
}
public function verify_nonce($nonce){
if ( ! wp_verify_nonce( $nonce, 'like_system' ) )
die ();
}
public function like_dislike_kernal(){
extract($_POST);
$this->verify_nonce($nonce);
$this->postid=$postid;
$this->userid=get_current_user_id();
$this->post_ko_like_count = get_post_meta( $postid, "_post_ko_like_count", true );
if($system=="like"){
if(is_user_logged_in()){
$this->logged_in_user_like_kernal();
}else{
$this->anonymous_user_like_kernal();
}
}
die();
}
private function make_array_if_not_exist($var){
if(!is_array($var)){
$var=[];
return $var;
}
return $var;
}
private function already_liked_or_disliked($whattocheck="liked"){
if(is_user_logged_in()){
$post_ma_like_garney_user=$this->make_array_if_not_exist(get_post_meta( $this->postid, "_post_ma_like_garney_user", true ));
if(in_array($this->userid,$post_ma_like_garney_user)) return true;
}
return false;
}
private function logged_in_user_like_kernal(){
$user_lay_like_gareko_posts=$this->make_array_if_not_exist(get_user_option( "_user_lay_like_gareko_posts", $this->userid ));
$post_ma_like_garney_user=$this->make_array_if_not_exist(get_post_meta( $this->postid, "_post_ma_like_garney_user", true ));
$user_lay_like_gareko_posts["Post_ID_".$this->postid]=$this->postid;
$post_ma_like_garney_user["User_ID_".$this->userid]=$this->userid;
if($this->already_liked_or_disliked()==false){
update_post_meta( $this->postid, "_post_ko_like_count", $this->post_ko_like_count + 1 );
echo $this->post_ko_like_count + 1; // update count on front end
}else{
$ukey= array_search( $this->userid, $post_ma_like_garney_user);
$pkey= array_search( $this->postid, $user_lay_like_gareko_posts );
unset( $user_lay_like_gareko_posts[$pkey] ); // remove from array
unset( $post_ma_like_garney_user[$ukey] ); // remove from array
update_post_meta( $this->postid, "_post_ko_like_count", --$this->post_ko_like_count );
echo $this->post_ko_like_count;
}
}
}
$like_system=new Like_System();
$like_system->load_our_ajax_script();
?>
</code></pre>
<p>Basically, when user click like button the ajax works and this like_system class works will add like count on data base by +1</p>
<p><strong>Problem</strong>
Everything works fine if user click like button slowly . For instance if i click like button and it showed like count 5. When i clicked like after 5 second(suppose) it will unlike and show like count 4 and as we expect if i click the like count will show 5.Like this here is one of test where i consoled log the like counter which toogle correctly when i click button after some interval.
<a href="https://i.stack.imgur.com/5OQpE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5OQpE.png" alt="enter image description here"></a></p>
<p>But supposed i clicked like button very fast say 5 times in a second . We might expect like count should toggle between 4 and 5 but it doesn't sometimes it shows -1 or -3 and sometime even 8 . Why is this happening ? </p>
<p>Here is the test when i click the like button very fast.
<a href="https://i.stack.imgur.com/WWgd5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WWgd5.png" alt="enter image description here"></a>
Digged in to code for hours but still cannot find any problem :( </p>
<p>I even don't know is ajax a problem or php problem :(
Thanks.</p>
|
[
{
"answer_id": 210911,
"author": "szabesz",
"author_id": 84818,
"author_profile": "https://wordpress.stackexchange.com/users/84818",
"pm_score": 0,
"selected": false,
"text": "<p>This is the solution I came up with: we can override the WooCommerce template file and change it. I do not like overriding template files, because in the future the WooCommerce template might change and we have to copy it again and apply the changes to the overriding template anyway, but I could not find an easier way to do it.</p>\n\n<p>From the WooCommerce plugin directory copy templates/myaccount/form-lost-password.php to woocommerce/myaccount/ into your (child) theme directory. (This is the way to override the standard WC template files)</p>\n\n<p>Apply the following changes (that is: add the lines ending in \"//added by Szabesz ?>\" to the copy of the template file):</p>\n\n<pre><code><?php wc_print_notices(); ?>\n<?php $on_result_page = isset($_POST['wc_reset_password']) && $_POST['wc_reset_password'] == \"true\"; //added by Szabesz ?>\n<?php $on_reset_true_page = isset($_GET['reset']) && $_GET['reset'] == \"true\"; //added by Szabesz ?>\n<form method=\"post\" class=\"lost_reset_password\">\n\n <?php if( 'lost_password' == $args['form'] ) : ?>\n <?php if( !$on_result_page && !$on_reset_true_page ) : //added by Szabesz ?>\n <p><?php echo apply_filters( 'woocommerce_lost_password_message', __( 'Lost your password? Please enter your username or email address. You will receive a link to create a new password via email.', 'woocommerce' ) ); ?></p>\n\n <p class=\"form-row form-row-first\"><label for=\"user_login\"><?php _e( 'Username or email', 'woocommerce' ); ?></label> <input class=\"input-text\" type=\"text\" name=\"user_login\" id=\"user_login\" /></p>\n <?php else : //added by Szabesz ?>\n <?php if ( !$on_reset_true_page ) : //added by Szabesz ?>\n If you want to use the form again, <a href=\"<?php echo esc_attr(wc_get_endpoint_url( 'lost-password', '', wc_get_page_permalink('myaccount') ) ); ?>\">please click here.</a><?php //added by Szabesz ?>\n <?php endif; //added by Szabesz ?>\n <?php endif; //added by Szabesz ?>\n <?php else : ?>\n\n <p><?php echo apply_filters( 'woocommerce_reset_password_message', __( 'Enter a new password below.', 'woocommerce') ); ?></p>\n\n <p class=\"form-row form-row-first\">\n <label for=\"password_1\"><?php _e( 'New password', 'woocommerce' ); ?> <span class=\"required\">*</span></label>\n <input type=\"password\" class=\"input-text\" name=\"password_1\" id=\"password_1\" />\n </p>\n <p class=\"form-row form-row-last\">\n <label for=\"password_2\"><?php _e( 'Re-enter new password', 'woocommerce' ); ?> <span class=\"required\">*</span></label>\n <input type=\"password\" class=\"input-text\" name=\"password_2\" id=\"password_2\" />\n </p>\n\n <input type=\"hidden\" name=\"reset_key\" value=\"<?php echo isset( $args['key'] ) ? $args['key'] : ''; ?>\" />\n <input type=\"hidden\" name=\"reset_login\" value=\"<?php echo isset( $args['login'] ) ? $args['login'] : ''; ?>\" />\n\n <?php endif; ?>\n\n <div class=\"clear\"></div>\n\n <?php do_action( 'woocommerce_lostpassword_form' ); ?>\n <?php if( $args['form'] == 'lost_password' && !$on_result_page && !$on_reset_true_page || $args['form'] == \"reset_password\" ) : //added by Szabesz ?>\n <p class=\"form-row\">\n <input type=\"hidden\" name=\"wc_reset_password\" value=\"true\" />\n <input type=\"submit\" class=\"button\" value=\"<?php echo 'lost_password' == $args['form'] ? __( 'Reset Password', 'woocommerce' ) : __( 'Save', 'woocommerce' ); ?>\" />\n </p>\n\n <?php wp_nonce_field( $args['form'] ); ?>\n <?php endif; //added by Szabesz ?>\n</form>\n</code></pre>\n\n<p>By using these if statements we check the different states of the lost-password page and change it accordingly.</p>\n\n<p>I expect the WooTheme devs to change this template in the future, since the default behavior is really confusing and I wonder why it is implemented in this way in the first place.</p>\n"
},
{
"answer_id": 211016,
"author": "Dennis",
"author_id": 82046,
"author_profile": "https://wordpress.stackexchange.com/users/82046",
"pm_score": 1,
"selected": false,
"text": "<p>I just found another solution to my problem. The problem was that the messages just wasn't displayed properly. By adding this code to my custom CSS (under \"Appearance\"), the messages are now shown again:</p>\n\n<pre><code>.page-id-1154 .woocommerce-message, .page-id-10 .woocommerce-message { \n display: block !important; \n}\n</code></pre>\n"
}
] |
2015/10/13
|
[
"https://wordpress.stackexchange.com/questions/207134",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80671/"
] |
I am creating a like system in PHP . My code looks like this .
```
<?php
class Like_System {
private $userid;
private $postid;
private $user_ko_like_count;
private $post_ko_like_count;
private $user_ko_dislike_count;
private $post_ko_dislike_count;
private $user_ip;
public function __construct(){
}
public function our_ajax_script(){
wp_enqueue_script( 'sb_like_post', get_template_directory_uri().'/data/js/post-like.min.js', false, '1.0', 1 );
wp_localize_script( 'sb_like_post', 'ajax_var', array(
'url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'like_system' )
)
);
}
public function load_our_ajax_script(){
add_action( 'init', array($this,"our_ajax_script") );
add_action( 'wp_ajax_nopriv_like_system',array($this,"like_dislike_kernal"));
add_action( 'wp_ajax_like_system',array($this,"like_dislike_kernal"));
}
public function verify_nonce($nonce){
if ( ! wp_verify_nonce( $nonce, 'like_system' ) )
die ();
}
public function like_dislike_kernal(){
extract($_POST);
$this->verify_nonce($nonce);
$this->postid=$postid;
$this->userid=get_current_user_id();
$this->post_ko_like_count = get_post_meta( $postid, "_post_ko_like_count", true );
if($system=="like"){
if(is_user_logged_in()){
$this->logged_in_user_like_kernal();
}else{
$this->anonymous_user_like_kernal();
}
}
die();
}
private function make_array_if_not_exist($var){
if(!is_array($var)){
$var=[];
return $var;
}
return $var;
}
private function already_liked_or_disliked($whattocheck="liked"){
if(is_user_logged_in()){
$post_ma_like_garney_user=$this->make_array_if_not_exist(get_post_meta( $this->postid, "_post_ma_like_garney_user", true ));
if(in_array($this->userid,$post_ma_like_garney_user)) return true;
}
return false;
}
private function logged_in_user_like_kernal(){
$user_lay_like_gareko_posts=$this->make_array_if_not_exist(get_user_option( "_user_lay_like_gareko_posts", $this->userid ));
$post_ma_like_garney_user=$this->make_array_if_not_exist(get_post_meta( $this->postid, "_post_ma_like_garney_user", true ));
$user_lay_like_gareko_posts["Post_ID_".$this->postid]=$this->postid;
$post_ma_like_garney_user["User_ID_".$this->userid]=$this->userid;
if($this->already_liked_or_disliked()==false){
update_post_meta( $this->postid, "_post_ko_like_count", $this->post_ko_like_count + 1 );
echo $this->post_ko_like_count + 1; // update count on front end
}else{
$ukey= array_search( $this->userid, $post_ma_like_garney_user);
$pkey= array_search( $this->postid, $user_lay_like_gareko_posts );
unset( $user_lay_like_gareko_posts[$pkey] ); // remove from array
unset( $post_ma_like_garney_user[$ukey] ); // remove from array
update_post_meta( $this->postid, "_post_ko_like_count", --$this->post_ko_like_count );
echo $this->post_ko_like_count;
}
}
}
$like_system=new Like_System();
$like_system->load_our_ajax_script();
?>
```
Basically, when user click like button the ajax works and this like\_system class works will add like count on data base by +1
**Problem**
Everything works fine if user click like button slowly . For instance if i click like button and it showed like count 5. When i clicked like after 5 second(suppose) it will unlike and show like count 4 and as we expect if i click the like count will show 5.Like this here is one of test where i consoled log the like counter which toogle correctly when i click button after some interval.
[](https://i.stack.imgur.com/5OQpE.png)
But supposed i clicked like button very fast say 5 times in a second . We might expect like count should toggle between 4 and 5 but it doesn't sometimes it shows -1 or -3 and sometime even 8 . Why is this happening ?
Here is the test when i click the like button very fast.
[](https://i.stack.imgur.com/WWgd5.png)
Digged in to code for hours but still cannot find any problem :(
I even don't know is ajax a problem or php problem :(
Thanks.
|
I just found another solution to my problem. The problem was that the messages just wasn't displayed properly. By adding this code to my custom CSS (under "Appearance"), the messages are now shown again:
```
.page-id-1154 .woocommerce-message, .page-id-10 .woocommerce-message {
display: block !important;
}
```
|
207,184 |
<p>I'm trying to create a feed where posts are pulled based off a set of authors, OR a set of categories, but I haven't had much luck. I've tried using <code>meta_query</code> and <code>tax_query</code>, but neither worked. Basically the query I'm trying to run is:</p>
<pre><code>"SELECT * FROM wp_posts WHERE author_id = $set_of_authors OR category = $set_of_categories"
</code></pre>
<p>I'm hoping to get a post object that I could just run through the loop normally, but I'll take what I can get. The only thing left I could think of was to run <code>get_results</code> with that query, but I know this is generally not the WordPress way. Is there a better way to get this query?</p>
|
[
{
"answer_id": 207713,
"author": "William Brawner",
"author_id": 82780,
"author_profile": "https://wordpress.stackexchange.com/users/82780",
"pm_score": 0,
"selected": false,
"text": "<p>Well, it's not pretty and I'm sure there are better ways to do this, but this is what I came up with: </p>\n\n<pre><code>if ($author_ids) {\n $author_ids = implode(',', $author_ids);\n}\nif ($cat_ids) {\n $cat_ids = implode(',', $cat_ids);\n}\nglobal $wpdb;\nif (count($author_ids) > 0 && count($cat_ids) > 0) {\n $posts = $wpdb->get_results(\n \"SELECT *\n FROM $wpdb->posts\n INNER JOIN $wpdb->term_relationships\n ON $wpdb->posts.ID = $wpdb->term_relationships.object_id\n WHERE post_status = 'publish'\n AND post_author\n IN ($author_ids)\n OR term_taxonomy_id\n IN ($cat_ids)\n ORDER BY post_date DESC\"\n );\n $post_ids = array();\n foreach ($posts as $post) {\n if (!in_array($post->ID, $post_ids)) {\n $post_ids[] = intval($post->ID);\n }\n }\n $post_ids = array_slice($post_ids, 0, 12);\n $query = new WP_Query(array('post__in' => $post_ids));\n} else if (count($author_ids > 0 ) && count($cat_ids) == 0) {\n $query = new WP_Query(\"author={$author_ids}&posts_per_page=12\");\n} else if (count($author_ids == 0 ) && count($cat_ids) > 0) {\n $query = new WP_Query(\"cat={$cat_ids}&posts_per_page=12\");\n}\n</code></pre>\n\n<p>In this particular case I was looking for 12 posts, so if someone needs more, just change the number 12 at the bottom for the number they need.</p>\n\n<p>I'm not sure why, but this line:</p>\n\n<pre><code> $post_ids = array_slice($post_ids, 0, 12);\n</code></pre>\n\n<p>had to be changed to this:</p>\n\n<pre><code> $post_ids = array_slice($post_ids, 0, 16);\n</code></pre>\n\n<p>because it was only printing 8 posts instead of 12, despite the logs saying that my $post_ids contained 12 post IDs. Anyways, this bit by itself shouldn't cause any problems for anyone else who looks to use it. Hopefully this helps or someone else knows of a better way to implement this.</p>\n"
},
{
"answer_id": 207876,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<h2>Custom feed slug</h2>\n\n<p>To create a custom feed slug, e.g. </p>\n\n<pre><code>example.tld/billyfeed/\n</code></pre>\n\n<p>we can use the <a href=\"https://codex.wordpress.org/Rewrite_API/add_feed\" rel=\"nofollow\"><code>add_feed()</code></a> but we have to flush the rewrite rules to activate it. We can do that e.g. by visiting the <em>Permalinks</em> settings page in the backend. </p>\n\n<p>To generate the feed we can use e.g. <code>do_feed_rss2()</code> or <code>do_feed_atom()</code>.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>add_action( 'init', function()\n{\n add_feed( 'billyfeed', function()\n {\n do_feed_rss2();\n });\n});\n</code></pre>\n\n<h2>Modify the custom feed query</h2>\n\n<p>Next we need to modify our custom feed so that we either get the <em>authors</em> or <em>categories</em>.</p>\n\n<p>Here's a workaround using the <code>posts_clauses</code> filter but without using string replacements with <code>str_replace()</code>.</p>\n\n<pre><code>/**\n * Custom feed example.tld/billyfeed that queries authors or categories\n * Supports pagination\n *\n * @link http://wordpress.stackexchange.com/a/207876/26350\n */\nadd_filter( 'posts_clauses', function( $clauses, \\WP_Query $q ) \n{ \n //---------------------------------------\n // Only target our custom feed\n //---------------------------------------\n if( ! $q->is_feed( 'billyfeed' ) || ! $q->is_main_query() )\n return $clauses;\n\n global $wpdb; \n\n //---------------------------------------\n // Input - we edit this to our needs\n //---------------------------------------\n $tax_query = [ \n [\n 'taxonomy' => 'category',\n 'field' => 'slug',\n 'terms' => [ 'red', 'green', 'blue' ]\n ]\n ]; \n $author__in = [ 1, 2, 3 ]; \n\n //---------------------------------------\n // Generate the tax query SQL\n //---------------------------------------\n $qv = [ 'tax_query' => $tax_query, 'cat' => null, 'tag' => null ];\n $q->parse_tax_query( $qv );\n $tc = $q->tax_query->get_sql( $wpdb->posts, 'ID' );\n\n //---------------------------------------\n // Generate the author query SQL\n //---------------------------------------\n $csv = join( ',', wp_parse_id_list( (array) $author__in ) );\n $authors = \" {$wpdb->posts}.post_author IN ( $csv ) \";\n\n //---------------------------------------\n // Make sure the authors are set and \n // the tax query is valid (doesn't contain 0 = 1)\n //---------------------------------------\n if( ! empty( $author__in ) && false === strpos ( $tc['where' ], ' 0 = 1' ) ) \n {\n // Append to the current join/where parts\n $clauses['join'] .= $tc['join'];\n $clauses['where'] .= sprintf( \n ' AND ( %s OR ( 1=1 %s ) ) ', // The tax query SQL comes prepended with AND\n $authors,\n $tc['where']\n );\n }\n\n return $clauses; \n\n}, PHP_INT_MAX, 2 );\n</code></pre>\n\n<p>where we modify the <code>$tax_query</code> and <code>$author__in</code> to our needs.</p>\n\n<p>This generates the following main SQL query:</p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID \nFROM wp_posts \nINNER JOIN wp_term_relationships \n ON (wp_posts.ID = wp_term_relationships.object_id) \nWHERE\n 1=1 \n AND wp_posts.post_type = 'post' \n AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') \n AND ( wp_posts.post_authors IN (1,2,3 ) OR ( 1=1 AND ( \n wp_term_relationships.term_taxonomy_id IN (1,43,120)\n ) ) ) \nORDER BY wp_posts.post_date DESC \nLIMIT 0, 10;\n</code></pre>\n\n<p>With this approach we can still paginate our feed:</p>\n\n<pre><code>example.tld/billyfeed/?paged=2\n</code></pre>\n"
}
] |
2015/10/30
|
[
"https://wordpress.stackexchange.com/questions/207184",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82780/"
] |
I'm trying to create a feed where posts are pulled based off a set of authors, OR a set of categories, but I haven't had much luck. I've tried using `meta_query` and `tax_query`, but neither worked. Basically the query I'm trying to run is:
```
"SELECT * FROM wp_posts WHERE author_id = $set_of_authors OR category = $set_of_categories"
```
I'm hoping to get a post object that I could just run through the loop normally, but I'll take what I can get. The only thing left I could think of was to run `get_results` with that query, but I know this is generally not the WordPress way. Is there a better way to get this query?
|
Custom feed slug
----------------
To create a custom feed slug, e.g.
```
example.tld/billyfeed/
```
we can use the [`add_feed()`](https://codex.wordpress.org/Rewrite_API/add_feed) but we have to flush the rewrite rules to activate it. We can do that e.g. by visiting the *Permalinks* settings page in the backend.
To generate the feed we can use e.g. `do_feed_rss2()` or `do_feed_atom()`.
Here's an example:
```
add_action( 'init', function()
{
add_feed( 'billyfeed', function()
{
do_feed_rss2();
});
});
```
Modify the custom feed query
----------------------------
Next we need to modify our custom feed so that we either get the *authors* or *categories*.
Here's a workaround using the `posts_clauses` filter but without using string replacements with `str_replace()`.
```
/**
* Custom feed example.tld/billyfeed that queries authors or categories
* Supports pagination
*
* @link http://wordpress.stackexchange.com/a/207876/26350
*/
add_filter( 'posts_clauses', function( $clauses, \WP_Query $q )
{
//---------------------------------------
// Only target our custom feed
//---------------------------------------
if( ! $q->is_feed( 'billyfeed' ) || ! $q->is_main_query() )
return $clauses;
global $wpdb;
//---------------------------------------
// Input - we edit this to our needs
//---------------------------------------
$tax_query = [
[
'taxonomy' => 'category',
'field' => 'slug',
'terms' => [ 'red', 'green', 'blue' ]
]
];
$author__in = [ 1, 2, 3 ];
//---------------------------------------
// Generate the tax query SQL
//---------------------------------------
$qv = [ 'tax_query' => $tax_query, 'cat' => null, 'tag' => null ];
$q->parse_tax_query( $qv );
$tc = $q->tax_query->get_sql( $wpdb->posts, 'ID' );
//---------------------------------------
// Generate the author query SQL
//---------------------------------------
$csv = join( ',', wp_parse_id_list( (array) $author__in ) );
$authors = " {$wpdb->posts}.post_author IN ( $csv ) ";
//---------------------------------------
// Make sure the authors are set and
// the tax query is valid (doesn't contain 0 = 1)
//---------------------------------------
if( ! empty( $author__in ) && false === strpos ( $tc['where' ], ' 0 = 1' ) )
{
// Append to the current join/where parts
$clauses['join'] .= $tc['join'];
$clauses['where'] .= sprintf(
' AND ( %s OR ( 1=1 %s ) ) ', // The tax query SQL comes prepended with AND
$authors,
$tc['where']
);
}
return $clauses;
}, PHP_INT_MAX, 2 );
```
where we modify the `$tax_query` and `$author__in` to our needs.
This generates the following main SQL query:
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
INNER JOIN wp_term_relationships
ON (wp_posts.ID = wp_term_relationships.object_id)
WHERE
1=1
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private')
AND ( wp_posts.post_authors IN (1,2,3 ) OR ( 1=1 AND (
wp_term_relationships.term_taxonomy_id IN (1,43,120)
) ) )
ORDER BY wp_posts.post_date DESC
LIMIT 0, 10;
```
With this approach we can still paginate our feed:
```
example.tld/billyfeed/?paged=2
```
|
207,189 |
<p>I have created a meta box for a theme I am working on, it is a simple meta box with a check box for featured post. The problem is user can tick that check box for <strong>multiple posts</strong> in the <strong>same category</strong>. </p>
<p>I want to disable the meta value from an old post once a new post published under that category. So basically only allow 1 post to be checked as featured on any given category. I think I should do something with </p>
<pre><code>delete_post_meta( $post_id, 'featured_post' );
</code></pre>
<p>but I am not sure how can I check previous posts and delete the post meta from them. Any suggestion?</p>
<p><strong>Update #1 :</strong></p>
<p>This is my meta box:</p>
<pre><code>//FEATURED POST CHECK BOX
//ADD THE META BOX
add_action( 'add_meta_boxes', 'add_featured_slide' );
function add_featured_slide(){
//POST TYPES TO HAVE THE CUSTOM META BOX
$ctptypes = array( 'post', 'page', 'your_custom_post_type' );
foreach ( $ctptypes as $ctptype ) {
add_meta_box( 'featured-slide', 'Featured Post', 'featured_slide_func', $ctptype, 'side', 'high' );
}
}
//DEFINE THE META BOX
function featured_slide_func( $post ){
$values = get_post_custom( $post->ID );
$check = isset( $values['special_box_check'] ) ? esc_attr( $values['special_box_check'][0] ) : '';
wp_nonce_field( 'my_featured_slide_nonce', 'featured_slide_nonce' );
?>
<p>
<input type="checkbox" name="special_box_check" id="special_box_check" <?php checked( $check, 'on' ); ?> />
<label for="special_box_check">Feature this post?</label>
</p>
<?php
}
//SAVE THE META BOX DATA WITH THE POST
add_action( 'save_post', 'featured_slide_save' );
function featured_slide_save( $post_id ){
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if( !isset( $_POST['featured_slide_nonce'] ) || !wp_verify_nonce( $_POST['featured_slide_nonce'], 'my_featured_slide_nonce' ) ) return;
if( !current_user_can( 'edit_post' ) ) return;
$allowed = array(
'a' => array(
'href' => array()
)
);
// IF CHECKED SAVE THE CUSTOM META
if ( isset( $_POST['special_box_check'] ) && $_POST['special_box_check'] ) {
add_post_meta( $post_id, 'special_box_check', 'on', true );
}
// IF UNCHECKED DELETE THE CUSTOM META
else {
delete_post_meta( $post_id, 'special_box_check' );
}
}
</code></pre>
|
[
{
"answer_id": 207713,
"author": "William Brawner",
"author_id": 82780,
"author_profile": "https://wordpress.stackexchange.com/users/82780",
"pm_score": 0,
"selected": false,
"text": "<p>Well, it's not pretty and I'm sure there are better ways to do this, but this is what I came up with: </p>\n\n<pre><code>if ($author_ids) {\n $author_ids = implode(',', $author_ids);\n}\nif ($cat_ids) {\n $cat_ids = implode(',', $cat_ids);\n}\nglobal $wpdb;\nif (count($author_ids) > 0 && count($cat_ids) > 0) {\n $posts = $wpdb->get_results(\n \"SELECT *\n FROM $wpdb->posts\n INNER JOIN $wpdb->term_relationships\n ON $wpdb->posts.ID = $wpdb->term_relationships.object_id\n WHERE post_status = 'publish'\n AND post_author\n IN ($author_ids)\n OR term_taxonomy_id\n IN ($cat_ids)\n ORDER BY post_date DESC\"\n );\n $post_ids = array();\n foreach ($posts as $post) {\n if (!in_array($post->ID, $post_ids)) {\n $post_ids[] = intval($post->ID);\n }\n }\n $post_ids = array_slice($post_ids, 0, 12);\n $query = new WP_Query(array('post__in' => $post_ids));\n} else if (count($author_ids > 0 ) && count($cat_ids) == 0) {\n $query = new WP_Query(\"author={$author_ids}&posts_per_page=12\");\n} else if (count($author_ids == 0 ) && count($cat_ids) > 0) {\n $query = new WP_Query(\"cat={$cat_ids}&posts_per_page=12\");\n}\n</code></pre>\n\n<p>In this particular case I was looking for 12 posts, so if someone needs more, just change the number 12 at the bottom for the number they need.</p>\n\n<p>I'm not sure why, but this line:</p>\n\n<pre><code> $post_ids = array_slice($post_ids, 0, 12);\n</code></pre>\n\n<p>had to be changed to this:</p>\n\n<pre><code> $post_ids = array_slice($post_ids, 0, 16);\n</code></pre>\n\n<p>because it was only printing 8 posts instead of 12, despite the logs saying that my $post_ids contained 12 post IDs. Anyways, this bit by itself shouldn't cause any problems for anyone else who looks to use it. Hopefully this helps or someone else knows of a better way to implement this.</p>\n"
},
{
"answer_id": 207876,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<h2>Custom feed slug</h2>\n\n<p>To create a custom feed slug, e.g. </p>\n\n<pre><code>example.tld/billyfeed/\n</code></pre>\n\n<p>we can use the <a href=\"https://codex.wordpress.org/Rewrite_API/add_feed\" rel=\"nofollow\"><code>add_feed()</code></a> but we have to flush the rewrite rules to activate it. We can do that e.g. by visiting the <em>Permalinks</em> settings page in the backend. </p>\n\n<p>To generate the feed we can use e.g. <code>do_feed_rss2()</code> or <code>do_feed_atom()</code>.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>add_action( 'init', function()\n{\n add_feed( 'billyfeed', function()\n {\n do_feed_rss2();\n });\n});\n</code></pre>\n\n<h2>Modify the custom feed query</h2>\n\n<p>Next we need to modify our custom feed so that we either get the <em>authors</em> or <em>categories</em>.</p>\n\n<p>Here's a workaround using the <code>posts_clauses</code> filter but without using string replacements with <code>str_replace()</code>.</p>\n\n<pre><code>/**\n * Custom feed example.tld/billyfeed that queries authors or categories\n * Supports pagination\n *\n * @link http://wordpress.stackexchange.com/a/207876/26350\n */\nadd_filter( 'posts_clauses', function( $clauses, \\WP_Query $q ) \n{ \n //---------------------------------------\n // Only target our custom feed\n //---------------------------------------\n if( ! $q->is_feed( 'billyfeed' ) || ! $q->is_main_query() )\n return $clauses;\n\n global $wpdb; \n\n //---------------------------------------\n // Input - we edit this to our needs\n //---------------------------------------\n $tax_query = [ \n [\n 'taxonomy' => 'category',\n 'field' => 'slug',\n 'terms' => [ 'red', 'green', 'blue' ]\n ]\n ]; \n $author__in = [ 1, 2, 3 ]; \n\n //---------------------------------------\n // Generate the tax query SQL\n //---------------------------------------\n $qv = [ 'tax_query' => $tax_query, 'cat' => null, 'tag' => null ];\n $q->parse_tax_query( $qv );\n $tc = $q->tax_query->get_sql( $wpdb->posts, 'ID' );\n\n //---------------------------------------\n // Generate the author query SQL\n //---------------------------------------\n $csv = join( ',', wp_parse_id_list( (array) $author__in ) );\n $authors = \" {$wpdb->posts}.post_author IN ( $csv ) \";\n\n //---------------------------------------\n // Make sure the authors are set and \n // the tax query is valid (doesn't contain 0 = 1)\n //---------------------------------------\n if( ! empty( $author__in ) && false === strpos ( $tc['where' ], ' 0 = 1' ) ) \n {\n // Append to the current join/where parts\n $clauses['join'] .= $tc['join'];\n $clauses['where'] .= sprintf( \n ' AND ( %s OR ( 1=1 %s ) ) ', // The tax query SQL comes prepended with AND\n $authors,\n $tc['where']\n );\n }\n\n return $clauses; \n\n}, PHP_INT_MAX, 2 );\n</code></pre>\n\n<p>where we modify the <code>$tax_query</code> and <code>$author__in</code> to our needs.</p>\n\n<p>This generates the following main SQL query:</p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID \nFROM wp_posts \nINNER JOIN wp_term_relationships \n ON (wp_posts.ID = wp_term_relationships.object_id) \nWHERE\n 1=1 \n AND wp_posts.post_type = 'post' \n AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') \n AND ( wp_posts.post_authors IN (1,2,3 ) OR ( 1=1 AND ( \n wp_term_relationships.term_taxonomy_id IN (1,43,120)\n ) ) ) \nORDER BY wp_posts.post_date DESC \nLIMIT 0, 10;\n</code></pre>\n\n<p>With this approach we can still paginate our feed:</p>\n\n<pre><code>example.tld/billyfeed/?paged=2\n</code></pre>\n"
}
] |
2015/10/31
|
[
"https://wordpress.stackexchange.com/questions/207189",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82260/"
] |
I have created a meta box for a theme I am working on, it is a simple meta box with a check box for featured post. The problem is user can tick that check box for **multiple posts** in the **same category**.
I want to disable the meta value from an old post once a new post published under that category. So basically only allow 1 post to be checked as featured on any given category. I think I should do something with
```
delete_post_meta( $post_id, 'featured_post' );
```
but I am not sure how can I check previous posts and delete the post meta from them. Any suggestion?
**Update #1 :**
This is my meta box:
```
//FEATURED POST CHECK BOX
//ADD THE META BOX
add_action( 'add_meta_boxes', 'add_featured_slide' );
function add_featured_slide(){
//POST TYPES TO HAVE THE CUSTOM META BOX
$ctptypes = array( 'post', 'page', 'your_custom_post_type' );
foreach ( $ctptypes as $ctptype ) {
add_meta_box( 'featured-slide', 'Featured Post', 'featured_slide_func', $ctptype, 'side', 'high' );
}
}
//DEFINE THE META BOX
function featured_slide_func( $post ){
$values = get_post_custom( $post->ID );
$check = isset( $values['special_box_check'] ) ? esc_attr( $values['special_box_check'][0] ) : '';
wp_nonce_field( 'my_featured_slide_nonce', 'featured_slide_nonce' );
?>
<p>
<input type="checkbox" name="special_box_check" id="special_box_check" <?php checked( $check, 'on' ); ?> />
<label for="special_box_check">Feature this post?</label>
</p>
<?php
}
//SAVE THE META BOX DATA WITH THE POST
add_action( 'save_post', 'featured_slide_save' );
function featured_slide_save( $post_id ){
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if( !isset( $_POST['featured_slide_nonce'] ) || !wp_verify_nonce( $_POST['featured_slide_nonce'], 'my_featured_slide_nonce' ) ) return;
if( !current_user_can( 'edit_post' ) ) return;
$allowed = array(
'a' => array(
'href' => array()
)
);
// IF CHECKED SAVE THE CUSTOM META
if ( isset( $_POST['special_box_check'] ) && $_POST['special_box_check'] ) {
add_post_meta( $post_id, 'special_box_check', 'on', true );
}
// IF UNCHECKED DELETE THE CUSTOM META
else {
delete_post_meta( $post_id, 'special_box_check' );
}
}
```
|
Custom feed slug
----------------
To create a custom feed slug, e.g.
```
example.tld/billyfeed/
```
we can use the [`add_feed()`](https://codex.wordpress.org/Rewrite_API/add_feed) but we have to flush the rewrite rules to activate it. We can do that e.g. by visiting the *Permalinks* settings page in the backend.
To generate the feed we can use e.g. `do_feed_rss2()` or `do_feed_atom()`.
Here's an example:
```
add_action( 'init', function()
{
add_feed( 'billyfeed', function()
{
do_feed_rss2();
});
});
```
Modify the custom feed query
----------------------------
Next we need to modify our custom feed so that we either get the *authors* or *categories*.
Here's a workaround using the `posts_clauses` filter but without using string replacements with `str_replace()`.
```
/**
* Custom feed example.tld/billyfeed that queries authors or categories
* Supports pagination
*
* @link http://wordpress.stackexchange.com/a/207876/26350
*/
add_filter( 'posts_clauses', function( $clauses, \WP_Query $q )
{
//---------------------------------------
// Only target our custom feed
//---------------------------------------
if( ! $q->is_feed( 'billyfeed' ) || ! $q->is_main_query() )
return $clauses;
global $wpdb;
//---------------------------------------
// Input - we edit this to our needs
//---------------------------------------
$tax_query = [
[
'taxonomy' => 'category',
'field' => 'slug',
'terms' => [ 'red', 'green', 'blue' ]
]
];
$author__in = [ 1, 2, 3 ];
//---------------------------------------
// Generate the tax query SQL
//---------------------------------------
$qv = [ 'tax_query' => $tax_query, 'cat' => null, 'tag' => null ];
$q->parse_tax_query( $qv );
$tc = $q->tax_query->get_sql( $wpdb->posts, 'ID' );
//---------------------------------------
// Generate the author query SQL
//---------------------------------------
$csv = join( ',', wp_parse_id_list( (array) $author__in ) );
$authors = " {$wpdb->posts}.post_author IN ( $csv ) ";
//---------------------------------------
// Make sure the authors are set and
// the tax query is valid (doesn't contain 0 = 1)
//---------------------------------------
if( ! empty( $author__in ) && false === strpos ( $tc['where' ], ' 0 = 1' ) )
{
// Append to the current join/where parts
$clauses['join'] .= $tc['join'];
$clauses['where'] .= sprintf(
' AND ( %s OR ( 1=1 %s ) ) ', // The tax query SQL comes prepended with AND
$authors,
$tc['where']
);
}
return $clauses;
}, PHP_INT_MAX, 2 );
```
where we modify the `$tax_query` and `$author__in` to our needs.
This generates the following main SQL query:
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
INNER JOIN wp_term_relationships
ON (wp_posts.ID = wp_term_relationships.object_id)
WHERE
1=1
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private')
AND ( wp_posts.post_authors IN (1,2,3 ) OR ( 1=1 AND (
wp_term_relationships.term_taxonomy_id IN (1,43,120)
) ) )
ORDER BY wp_posts.post_date DESC
LIMIT 0, 10;
```
With this approach we can still paginate our feed:
```
example.tld/billyfeed/?paged=2
```
|
207,199 |
<p>I duplicated my Wordpress installation to move to another server. Everything works find except one single file. I created a header-shop.php file to call a certain menu on my shop page. In the first server it was working. In the new one, it doesn't. It seems to me really crazy.</p>
<p>Here is the file:</p>
<pre><code><!doctype html>
<?php get_header(); ?>
<section class="grid wrapper shoptopmenu" id="content">
<div class="shop-menu">
<?php
$defaults = array(
'menu' => 'shop-top-menu',
'container' => 'nav',
'container_class' => 'grid wrapper',
'container_id' => 'shopmenue',
'menu_class' => 'unit full grid',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '',
'after' => '',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'depth' => 0,
'walker' => ''
);
wp_nav_menu( $defaults );
?>
</div>
</code></pre>
<p>In the first server, the HTML code is:</p>
<pre><code><section class="grid wrapper shoptopmenu" id="content">
<div class="shop-menu">
<nav id="shopmenue" class="grid wrapper">
<ul id="menu-shop-top-menu" class="unit full grid">
.....
</ul>
</nav>
</code></pre>
<p>In the new server, the HTML code is:</p>
<pre><code><section class="grid wrapper shoptopmenu" id="content">
<div class="shop-menu">
<div class="unit full grid">
<ul>
....
</ul>
</div>
</code></pre>
<p>You can see that the <code>nav</code> element and the id and class on the <code>ul</code> element are missing. Everything else is the same. Any idea before get crazy? :P</p>
|
[
{
"answer_id": 207713,
"author": "William Brawner",
"author_id": 82780,
"author_profile": "https://wordpress.stackexchange.com/users/82780",
"pm_score": 0,
"selected": false,
"text": "<p>Well, it's not pretty and I'm sure there are better ways to do this, but this is what I came up with: </p>\n\n<pre><code>if ($author_ids) {\n $author_ids = implode(',', $author_ids);\n}\nif ($cat_ids) {\n $cat_ids = implode(',', $cat_ids);\n}\nglobal $wpdb;\nif (count($author_ids) > 0 && count($cat_ids) > 0) {\n $posts = $wpdb->get_results(\n \"SELECT *\n FROM $wpdb->posts\n INNER JOIN $wpdb->term_relationships\n ON $wpdb->posts.ID = $wpdb->term_relationships.object_id\n WHERE post_status = 'publish'\n AND post_author\n IN ($author_ids)\n OR term_taxonomy_id\n IN ($cat_ids)\n ORDER BY post_date DESC\"\n );\n $post_ids = array();\n foreach ($posts as $post) {\n if (!in_array($post->ID, $post_ids)) {\n $post_ids[] = intval($post->ID);\n }\n }\n $post_ids = array_slice($post_ids, 0, 12);\n $query = new WP_Query(array('post__in' => $post_ids));\n} else if (count($author_ids > 0 ) && count($cat_ids) == 0) {\n $query = new WP_Query(\"author={$author_ids}&posts_per_page=12\");\n} else if (count($author_ids == 0 ) && count($cat_ids) > 0) {\n $query = new WP_Query(\"cat={$cat_ids}&posts_per_page=12\");\n}\n</code></pre>\n\n<p>In this particular case I was looking for 12 posts, so if someone needs more, just change the number 12 at the bottom for the number they need.</p>\n\n<p>I'm not sure why, but this line:</p>\n\n<pre><code> $post_ids = array_slice($post_ids, 0, 12);\n</code></pre>\n\n<p>had to be changed to this:</p>\n\n<pre><code> $post_ids = array_slice($post_ids, 0, 16);\n</code></pre>\n\n<p>because it was only printing 8 posts instead of 12, despite the logs saying that my $post_ids contained 12 post IDs. Anyways, this bit by itself shouldn't cause any problems for anyone else who looks to use it. Hopefully this helps or someone else knows of a better way to implement this.</p>\n"
},
{
"answer_id": 207876,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<h2>Custom feed slug</h2>\n\n<p>To create a custom feed slug, e.g. </p>\n\n<pre><code>example.tld/billyfeed/\n</code></pre>\n\n<p>we can use the <a href=\"https://codex.wordpress.org/Rewrite_API/add_feed\" rel=\"nofollow\"><code>add_feed()</code></a> but we have to flush the rewrite rules to activate it. We can do that e.g. by visiting the <em>Permalinks</em> settings page in the backend. </p>\n\n<p>To generate the feed we can use e.g. <code>do_feed_rss2()</code> or <code>do_feed_atom()</code>.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>add_action( 'init', function()\n{\n add_feed( 'billyfeed', function()\n {\n do_feed_rss2();\n });\n});\n</code></pre>\n\n<h2>Modify the custom feed query</h2>\n\n<p>Next we need to modify our custom feed so that we either get the <em>authors</em> or <em>categories</em>.</p>\n\n<p>Here's a workaround using the <code>posts_clauses</code> filter but without using string replacements with <code>str_replace()</code>.</p>\n\n<pre><code>/**\n * Custom feed example.tld/billyfeed that queries authors or categories\n * Supports pagination\n *\n * @link http://wordpress.stackexchange.com/a/207876/26350\n */\nadd_filter( 'posts_clauses', function( $clauses, \\WP_Query $q ) \n{ \n //---------------------------------------\n // Only target our custom feed\n //---------------------------------------\n if( ! $q->is_feed( 'billyfeed' ) || ! $q->is_main_query() )\n return $clauses;\n\n global $wpdb; \n\n //---------------------------------------\n // Input - we edit this to our needs\n //---------------------------------------\n $tax_query = [ \n [\n 'taxonomy' => 'category',\n 'field' => 'slug',\n 'terms' => [ 'red', 'green', 'blue' ]\n ]\n ]; \n $author__in = [ 1, 2, 3 ]; \n\n //---------------------------------------\n // Generate the tax query SQL\n //---------------------------------------\n $qv = [ 'tax_query' => $tax_query, 'cat' => null, 'tag' => null ];\n $q->parse_tax_query( $qv );\n $tc = $q->tax_query->get_sql( $wpdb->posts, 'ID' );\n\n //---------------------------------------\n // Generate the author query SQL\n //---------------------------------------\n $csv = join( ',', wp_parse_id_list( (array) $author__in ) );\n $authors = \" {$wpdb->posts}.post_author IN ( $csv ) \";\n\n //---------------------------------------\n // Make sure the authors are set and \n // the tax query is valid (doesn't contain 0 = 1)\n //---------------------------------------\n if( ! empty( $author__in ) && false === strpos ( $tc['where' ], ' 0 = 1' ) ) \n {\n // Append to the current join/where parts\n $clauses['join'] .= $tc['join'];\n $clauses['where'] .= sprintf( \n ' AND ( %s OR ( 1=1 %s ) ) ', // The tax query SQL comes prepended with AND\n $authors,\n $tc['where']\n );\n }\n\n return $clauses; \n\n}, PHP_INT_MAX, 2 );\n</code></pre>\n\n<p>where we modify the <code>$tax_query</code> and <code>$author__in</code> to our needs.</p>\n\n<p>This generates the following main SQL query:</p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID \nFROM wp_posts \nINNER JOIN wp_term_relationships \n ON (wp_posts.ID = wp_term_relationships.object_id) \nWHERE\n 1=1 \n AND wp_posts.post_type = 'post' \n AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') \n AND ( wp_posts.post_authors IN (1,2,3 ) OR ( 1=1 AND ( \n wp_term_relationships.term_taxonomy_id IN (1,43,120)\n ) ) ) \nORDER BY wp_posts.post_date DESC \nLIMIT 0, 10;\n</code></pre>\n\n<p>With this approach we can still paginate our feed:</p>\n\n<pre><code>example.tld/billyfeed/?paged=2\n</code></pre>\n"
}
] |
2015/10/31
|
[
"https://wordpress.stackexchange.com/questions/207199",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40793/"
] |
I duplicated my Wordpress installation to move to another server. Everything works find except one single file. I created a header-shop.php file to call a certain menu on my shop page. In the first server it was working. In the new one, it doesn't. It seems to me really crazy.
Here is the file:
```
<!doctype html>
<?php get_header(); ?>
<section class="grid wrapper shoptopmenu" id="content">
<div class="shop-menu">
<?php
$defaults = array(
'menu' => 'shop-top-menu',
'container' => 'nav',
'container_class' => 'grid wrapper',
'container_id' => 'shopmenue',
'menu_class' => 'unit full grid',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '',
'after' => '',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'depth' => 0,
'walker' => ''
);
wp_nav_menu( $defaults );
?>
</div>
```
In the first server, the HTML code is:
```
<section class="grid wrapper shoptopmenu" id="content">
<div class="shop-menu">
<nav id="shopmenue" class="grid wrapper">
<ul id="menu-shop-top-menu" class="unit full grid">
.....
</ul>
</nav>
```
In the new server, the HTML code is:
```
<section class="grid wrapper shoptopmenu" id="content">
<div class="shop-menu">
<div class="unit full grid">
<ul>
....
</ul>
</div>
```
You can see that the `nav` element and the id and class on the `ul` element are missing. Everything else is the same. Any idea before get crazy? :P
|
Custom feed slug
----------------
To create a custom feed slug, e.g.
```
example.tld/billyfeed/
```
we can use the [`add_feed()`](https://codex.wordpress.org/Rewrite_API/add_feed) but we have to flush the rewrite rules to activate it. We can do that e.g. by visiting the *Permalinks* settings page in the backend.
To generate the feed we can use e.g. `do_feed_rss2()` or `do_feed_atom()`.
Here's an example:
```
add_action( 'init', function()
{
add_feed( 'billyfeed', function()
{
do_feed_rss2();
});
});
```
Modify the custom feed query
----------------------------
Next we need to modify our custom feed so that we either get the *authors* or *categories*.
Here's a workaround using the `posts_clauses` filter but without using string replacements with `str_replace()`.
```
/**
* Custom feed example.tld/billyfeed that queries authors or categories
* Supports pagination
*
* @link http://wordpress.stackexchange.com/a/207876/26350
*/
add_filter( 'posts_clauses', function( $clauses, \WP_Query $q )
{
//---------------------------------------
// Only target our custom feed
//---------------------------------------
if( ! $q->is_feed( 'billyfeed' ) || ! $q->is_main_query() )
return $clauses;
global $wpdb;
//---------------------------------------
// Input - we edit this to our needs
//---------------------------------------
$tax_query = [
[
'taxonomy' => 'category',
'field' => 'slug',
'terms' => [ 'red', 'green', 'blue' ]
]
];
$author__in = [ 1, 2, 3 ];
//---------------------------------------
// Generate the tax query SQL
//---------------------------------------
$qv = [ 'tax_query' => $tax_query, 'cat' => null, 'tag' => null ];
$q->parse_tax_query( $qv );
$tc = $q->tax_query->get_sql( $wpdb->posts, 'ID' );
//---------------------------------------
// Generate the author query SQL
//---------------------------------------
$csv = join( ',', wp_parse_id_list( (array) $author__in ) );
$authors = " {$wpdb->posts}.post_author IN ( $csv ) ";
//---------------------------------------
// Make sure the authors are set and
// the tax query is valid (doesn't contain 0 = 1)
//---------------------------------------
if( ! empty( $author__in ) && false === strpos ( $tc['where' ], ' 0 = 1' ) )
{
// Append to the current join/where parts
$clauses['join'] .= $tc['join'];
$clauses['where'] .= sprintf(
' AND ( %s OR ( 1=1 %s ) ) ', // The tax query SQL comes prepended with AND
$authors,
$tc['where']
);
}
return $clauses;
}, PHP_INT_MAX, 2 );
```
where we modify the `$tax_query` and `$author__in` to our needs.
This generates the following main SQL query:
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
INNER JOIN wp_term_relationships
ON (wp_posts.ID = wp_term_relationships.object_id)
WHERE
1=1
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private')
AND ( wp_posts.post_authors IN (1,2,3 ) OR ( 1=1 AND (
wp_term_relationships.term_taxonomy_id IN (1,43,120)
) ) )
ORDER BY wp_posts.post_date DESC
LIMIT 0, 10;
```
With this approach we can still paginate our feed:
```
example.tld/billyfeed/?paged=2
```
|
207,219 |
<p>I am trying to add some text to the <code>customer-order-processing</code> email from WooCommerce, and it should ONLY be added in this particular email and ONLY if chosen payment method is Paypal. I have come so far as the text is added, and only when Paypal is chosen as payment method, but the text is displayed in every email to the customer now, for example also in the <code>order-completed</code> email or <code>customer-note</code> email. I have the following:</p>
<pre><code>add_action( 'woocommerce_email_before_order_table', 'add_order_email_instructions', 0, 2 );
function add_order_email_instructions( $order, $sent_to_admin ) {
if ( 'paypal' == $order->payment_method && ! $sent_to_admin ) {
echo 'my text:';
}
}
</code></pre>
<p>I have tried with additional conditionals, like <code>! $order->has_status( 'processing' )</code>, but nothing is working.</p>
|
[
{
"answer_id": 207713,
"author": "William Brawner",
"author_id": 82780,
"author_profile": "https://wordpress.stackexchange.com/users/82780",
"pm_score": 0,
"selected": false,
"text": "<p>Well, it's not pretty and I'm sure there are better ways to do this, but this is what I came up with: </p>\n\n<pre><code>if ($author_ids) {\n $author_ids = implode(',', $author_ids);\n}\nif ($cat_ids) {\n $cat_ids = implode(',', $cat_ids);\n}\nglobal $wpdb;\nif (count($author_ids) > 0 && count($cat_ids) > 0) {\n $posts = $wpdb->get_results(\n \"SELECT *\n FROM $wpdb->posts\n INNER JOIN $wpdb->term_relationships\n ON $wpdb->posts.ID = $wpdb->term_relationships.object_id\n WHERE post_status = 'publish'\n AND post_author\n IN ($author_ids)\n OR term_taxonomy_id\n IN ($cat_ids)\n ORDER BY post_date DESC\"\n );\n $post_ids = array();\n foreach ($posts as $post) {\n if (!in_array($post->ID, $post_ids)) {\n $post_ids[] = intval($post->ID);\n }\n }\n $post_ids = array_slice($post_ids, 0, 12);\n $query = new WP_Query(array('post__in' => $post_ids));\n} else if (count($author_ids > 0 ) && count($cat_ids) == 0) {\n $query = new WP_Query(\"author={$author_ids}&posts_per_page=12\");\n} else if (count($author_ids == 0 ) && count($cat_ids) > 0) {\n $query = new WP_Query(\"cat={$cat_ids}&posts_per_page=12\");\n}\n</code></pre>\n\n<p>In this particular case I was looking for 12 posts, so if someone needs more, just change the number 12 at the bottom for the number they need.</p>\n\n<p>I'm not sure why, but this line:</p>\n\n<pre><code> $post_ids = array_slice($post_ids, 0, 12);\n</code></pre>\n\n<p>had to be changed to this:</p>\n\n<pre><code> $post_ids = array_slice($post_ids, 0, 16);\n</code></pre>\n\n<p>because it was only printing 8 posts instead of 12, despite the logs saying that my $post_ids contained 12 post IDs. Anyways, this bit by itself shouldn't cause any problems for anyone else who looks to use it. Hopefully this helps or someone else knows of a better way to implement this.</p>\n"
},
{
"answer_id": 207876,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<h2>Custom feed slug</h2>\n\n<p>To create a custom feed slug, e.g. </p>\n\n<pre><code>example.tld/billyfeed/\n</code></pre>\n\n<p>we can use the <a href=\"https://codex.wordpress.org/Rewrite_API/add_feed\" rel=\"nofollow\"><code>add_feed()</code></a> but we have to flush the rewrite rules to activate it. We can do that e.g. by visiting the <em>Permalinks</em> settings page in the backend. </p>\n\n<p>To generate the feed we can use e.g. <code>do_feed_rss2()</code> or <code>do_feed_atom()</code>.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>add_action( 'init', function()\n{\n add_feed( 'billyfeed', function()\n {\n do_feed_rss2();\n });\n});\n</code></pre>\n\n<h2>Modify the custom feed query</h2>\n\n<p>Next we need to modify our custom feed so that we either get the <em>authors</em> or <em>categories</em>.</p>\n\n<p>Here's a workaround using the <code>posts_clauses</code> filter but without using string replacements with <code>str_replace()</code>.</p>\n\n<pre><code>/**\n * Custom feed example.tld/billyfeed that queries authors or categories\n * Supports pagination\n *\n * @link http://wordpress.stackexchange.com/a/207876/26350\n */\nadd_filter( 'posts_clauses', function( $clauses, \\WP_Query $q ) \n{ \n //---------------------------------------\n // Only target our custom feed\n //---------------------------------------\n if( ! $q->is_feed( 'billyfeed' ) || ! $q->is_main_query() )\n return $clauses;\n\n global $wpdb; \n\n //---------------------------------------\n // Input - we edit this to our needs\n //---------------------------------------\n $tax_query = [ \n [\n 'taxonomy' => 'category',\n 'field' => 'slug',\n 'terms' => [ 'red', 'green', 'blue' ]\n ]\n ]; \n $author__in = [ 1, 2, 3 ]; \n\n //---------------------------------------\n // Generate the tax query SQL\n //---------------------------------------\n $qv = [ 'tax_query' => $tax_query, 'cat' => null, 'tag' => null ];\n $q->parse_tax_query( $qv );\n $tc = $q->tax_query->get_sql( $wpdb->posts, 'ID' );\n\n //---------------------------------------\n // Generate the author query SQL\n //---------------------------------------\n $csv = join( ',', wp_parse_id_list( (array) $author__in ) );\n $authors = \" {$wpdb->posts}.post_author IN ( $csv ) \";\n\n //---------------------------------------\n // Make sure the authors are set and \n // the tax query is valid (doesn't contain 0 = 1)\n //---------------------------------------\n if( ! empty( $author__in ) && false === strpos ( $tc['where' ], ' 0 = 1' ) ) \n {\n // Append to the current join/where parts\n $clauses['join'] .= $tc['join'];\n $clauses['where'] .= sprintf( \n ' AND ( %s OR ( 1=1 %s ) ) ', // The tax query SQL comes prepended with AND\n $authors,\n $tc['where']\n );\n }\n\n return $clauses; \n\n}, PHP_INT_MAX, 2 );\n</code></pre>\n\n<p>where we modify the <code>$tax_query</code> and <code>$author__in</code> to our needs.</p>\n\n<p>This generates the following main SQL query:</p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID \nFROM wp_posts \nINNER JOIN wp_term_relationships \n ON (wp_posts.ID = wp_term_relationships.object_id) \nWHERE\n 1=1 \n AND wp_posts.post_type = 'post' \n AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') \n AND ( wp_posts.post_authors IN (1,2,3 ) OR ( 1=1 AND ( \n wp_term_relationships.term_taxonomy_id IN (1,43,120)\n ) ) ) \nORDER BY wp_posts.post_date DESC \nLIMIT 0, 10;\n</code></pre>\n\n<p>With this approach we can still paginate our feed:</p>\n\n<pre><code>example.tld/billyfeed/?paged=2\n</code></pre>\n"
}
] |
2015/10/31
|
[
"https://wordpress.stackexchange.com/questions/207219",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82798/"
] |
I am trying to add some text to the `customer-order-processing` email from WooCommerce, and it should ONLY be added in this particular email and ONLY if chosen payment method is Paypal. I have come so far as the text is added, and only when Paypal is chosen as payment method, but the text is displayed in every email to the customer now, for example also in the `order-completed` email or `customer-note` email. I have the following:
```
add_action( 'woocommerce_email_before_order_table', 'add_order_email_instructions', 0, 2 );
function add_order_email_instructions( $order, $sent_to_admin ) {
if ( 'paypal' == $order->payment_method && ! $sent_to_admin ) {
echo 'my text:';
}
}
```
I have tried with additional conditionals, like `! $order->has_status( 'processing' )`, but nothing is working.
|
Custom feed slug
----------------
To create a custom feed slug, e.g.
```
example.tld/billyfeed/
```
we can use the [`add_feed()`](https://codex.wordpress.org/Rewrite_API/add_feed) but we have to flush the rewrite rules to activate it. We can do that e.g. by visiting the *Permalinks* settings page in the backend.
To generate the feed we can use e.g. `do_feed_rss2()` or `do_feed_atom()`.
Here's an example:
```
add_action( 'init', function()
{
add_feed( 'billyfeed', function()
{
do_feed_rss2();
});
});
```
Modify the custom feed query
----------------------------
Next we need to modify our custom feed so that we either get the *authors* or *categories*.
Here's a workaround using the `posts_clauses` filter but without using string replacements with `str_replace()`.
```
/**
* Custom feed example.tld/billyfeed that queries authors or categories
* Supports pagination
*
* @link http://wordpress.stackexchange.com/a/207876/26350
*/
add_filter( 'posts_clauses', function( $clauses, \WP_Query $q )
{
//---------------------------------------
// Only target our custom feed
//---------------------------------------
if( ! $q->is_feed( 'billyfeed' ) || ! $q->is_main_query() )
return $clauses;
global $wpdb;
//---------------------------------------
// Input - we edit this to our needs
//---------------------------------------
$tax_query = [
[
'taxonomy' => 'category',
'field' => 'slug',
'terms' => [ 'red', 'green', 'blue' ]
]
];
$author__in = [ 1, 2, 3 ];
//---------------------------------------
// Generate the tax query SQL
//---------------------------------------
$qv = [ 'tax_query' => $tax_query, 'cat' => null, 'tag' => null ];
$q->parse_tax_query( $qv );
$tc = $q->tax_query->get_sql( $wpdb->posts, 'ID' );
//---------------------------------------
// Generate the author query SQL
//---------------------------------------
$csv = join( ',', wp_parse_id_list( (array) $author__in ) );
$authors = " {$wpdb->posts}.post_author IN ( $csv ) ";
//---------------------------------------
// Make sure the authors are set and
// the tax query is valid (doesn't contain 0 = 1)
//---------------------------------------
if( ! empty( $author__in ) && false === strpos ( $tc['where' ], ' 0 = 1' ) )
{
// Append to the current join/where parts
$clauses['join'] .= $tc['join'];
$clauses['where'] .= sprintf(
' AND ( %s OR ( 1=1 %s ) ) ', // The tax query SQL comes prepended with AND
$authors,
$tc['where']
);
}
return $clauses;
}, PHP_INT_MAX, 2 );
```
where we modify the `$tax_query` and `$author__in` to our needs.
This generates the following main SQL query:
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
INNER JOIN wp_term_relationships
ON (wp_posts.ID = wp_term_relationships.object_id)
WHERE
1=1
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private')
AND ( wp_posts.post_authors IN (1,2,3 ) OR ( 1=1 AND (
wp_term_relationships.term_taxonomy_id IN (1,43,120)
) ) )
ORDER BY wp_posts.post_date DESC
LIMIT 0, 10;
```
With this approach we can still paginate our feed:
```
example.tld/billyfeed/?paged=2
```
|
207,225 |
<p>I would like to filter all the options values, but the option filters are option specific.
Is there a way I could do something like</p>
<pre><code>add_filter('pre_option_*', 'my_check');
</code></pre>
<p>?</p>
|
[
{
"answer_id": 207230,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 0,
"selected": false,
"text": "<p>I suppose you could use <code>wp_load_alloptions()</code> and add a filter for each:</p>\n\n<pre><code>foreach ( array_keys( wp_load_alloptions() ) as $option ) {\n add_filter( 'pre_option_' . $option, function ( $pre ) use ( $option ) {\n // blah\n return $pre;\n } );\n}\n</code></pre>\n"
},
{
"answer_id": 231231,
"author": "Tomas",
"author_id": 32177,
"author_profile": "https://wordpress.stackexchange.com/users/32177",
"pm_score": 3,
"selected": true,
"text": "<p>I've tried the same thing and was able to hook into the <code>pre_option_</code> filter by using <code>all</code> as filter.</p>\n\n<pre><code>add_filter('all', 'pre_option_',1,3);\n\nfunction pre_option_($actionHook,$bool=false,$option_name)\n{\n if(strpos($actionHook,'pre_option_') === FALSE){\n return $bool;\n }\n}\n</code></pre>\n"
}
] |
2015/10/31
|
[
"https://wordpress.stackexchange.com/questions/207225",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/49220/"
] |
I would like to filter all the options values, but the option filters are option specific.
Is there a way I could do something like
```
add_filter('pre_option_*', 'my_check');
```
?
|
I've tried the same thing and was able to hook into the `pre_option_` filter by using `all` as filter.
```
add_filter('all', 'pre_option_',1,3);
function pre_option_($actionHook,$bool=false,$option_name)
{
if(strpos($actionHook,'pre_option_') === FALSE){
return $bool;
}
}
```
|
207,259 |
<p>I've been trying to get post format to work for a while now, and for some reasons it is still not working the way it should.</p>
<p>I am creating a custom theme based on HTML5 Blank theme.</p>
<p>First thing I did was to add post_formats to functions.php</p>
<pre><code>function add_post_formats() {
add_theme_support( 'post-formats', array( 'gallery', 'quote', 'video', 'aside', 'image', 'link', 'audio' ) );}
</code></pre>
<p>Post formats are now called in wp-admin and I can see the box for choosing the post_format in "Add new post".
I then added this code to my loop.php to set the post format to a specific post</p>
<pre><code><?php if (have_posts()): while (have_posts()) : the_post(); if(!get_post_format()) {
get_template_part('format', 'standard');
} else {
get_template_part('format', get_post_format());
} ?>
</code></pre>
<p>But something is still missing because each post has a format attached to it, but It does not change anything on the display. For example format-video or format-links looks exactly the same as a standard format.
In other words, embedded videos (for ex.) are not displayed on my article home page even though the post format is set and the video url is embedded in the content.</p>
<p>I am missing something, or doing someting wrong, and I've been struggling with this for hours, even though I read the codex again and again.
Could anyone tell me what am I doing wrong ?</p>
|
[
{
"answer_id": 207264,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Post formats are not magic. Your theme needs to actually have a code to generate different HTML (or apply different CSS rules) for different format. </p>\n\n<p>Having the theme \"suuport\" post formats is nice for future compatibility of the content, but by itself it doesn't do anything to how the content is displayed.</p>\n"
},
{
"answer_id": 212263,
"author": "Madivad",
"author_id": 37314,
"author_profile": "https://wordpress.stackexchange.com/users/37314",
"pm_score": 0,
"selected": false,
"text": "<p>I just posted a very similar answer here:<br>\n<a href=\"https://wordpress.stackexchange.com/a/212261/37314\">https://wordpress.stackexchange.com/a/212261/37314</a></p>\n\n<p>summarised here:</p>\n\n<blockquote>\n <p>Mostly you would make CSS changes. For example, a post that has the\n <code>aside</code> format will have included in it's mark-up a class of\n <code>format-aside</code> which you could override in your own CSS, whether it be\n by way of child theme support or CSS plugin.</p>\n \n <p>I've only just been playing with this today (incidentally, which is\n how I came across this question). </p>\n \n <p><strong>Example:</strong> You could hide the title of posts tagged with the <code>quote</code> post-format (ie <code>format-quote</code>) by including this in your CSS file:</p>\n\n<pre><code>.home .format-quote .entry-title {\n display: none;\n}\n</code></pre>\n \n <p>This would then format that entry on your blog page / index to not\n include the title from the post, and would make the quote just appear\n as more of an inline quote between two posts.</p>\n</blockquote>\n\n<p>here are two reference posts for you to have a look at:</p>\n\n<p><a href=\"https://codex.wordpress.org/User:Chipbennett/Post_Formats\" rel=\"nofollow noreferrer\">WordPress Codex page on Post Formats</a><br>\n<a href=\"https://www.elegantthemes.com/blog/tips-tricks/how-to-create-wordpress-post-formats\" rel=\"nofollow noreferrer\">Elegant Themes Blog post: Creating Post Formats</a></p>\n"
}
] |
2015/11/01
|
[
"https://wordpress.stackexchange.com/questions/207259",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76033/"
] |
I've been trying to get post format to work for a while now, and for some reasons it is still not working the way it should.
I am creating a custom theme based on HTML5 Blank theme.
First thing I did was to add post\_formats to functions.php
```
function add_post_formats() {
add_theme_support( 'post-formats', array( 'gallery', 'quote', 'video', 'aside', 'image', 'link', 'audio' ) );}
```
Post formats are now called in wp-admin and I can see the box for choosing the post\_format in "Add new post".
I then added this code to my loop.php to set the post format to a specific post
```
<?php if (have_posts()): while (have_posts()) : the_post(); if(!get_post_format()) {
get_template_part('format', 'standard');
} else {
get_template_part('format', get_post_format());
} ?>
```
But something is still missing because each post has a format attached to it, but It does not change anything on the display. For example format-video or format-links looks exactly the same as a standard format.
In other words, embedded videos (for ex.) are not displayed on my article home page even though the post format is set and the video url is embedded in the content.
I am missing something, or doing someting wrong, and I've been struggling with this for hours, even though I read the codex again and again.
Could anyone tell me what am I doing wrong ?
|
Post formats are not magic. Your theme needs to actually have a code to generate different HTML (or apply different CSS rules) for different format.
Having the theme "suuport" post formats is nice for future compatibility of the content, but by itself it doesn't do anything to how the content is displayed.
|
207,261 |
<p>For activation hooks codex states that you have to be explicit on globals:</p>
<p><a href="https://codex.wordpress.org/Function_Reference/register_activation_hook#A_Note_on_Variable_Scope" rel="nofollow">A note on variables during activation</a></p>
<p>But that seems not to be working on uninstall.php</p>
<p>If i define a global in my main plugin file like this:</p>
<pre><code>global $plugin_options_name;
$plugin_options_name = 'xxxxxxxxx';
</code></pre>
<p>Activation hook can use it via global statement , whereas uninstall.php cannot.</p>
<p>I have to redeclare the variable inside unistall.php</p>
<p>If this is the case, if i switch to uninstallation hook this will change?</p>
|
[
{
"answer_id": 207263,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": true,
"text": "<p>You should prefer the uninstall hook over the file if your main plugin doesn't have side effects (outputs html or writes to file/DB automatically when loaded). IMO there is too much risk (i.e. non zero) of doing the uninstall.php code wrong and open the file to direct execution from the outside.\nThis also help in having all the relevant code in one place.</p>\n\n<p>uninstall.php, when exists, is being executed without loading the plugin code (that is the whole point of it) and therefor whatever is declared in the plugin code will not be available to uninstall.php.</p>\n"
},
{
"answer_id": 207296,
"author": "J.D.",
"author_id": 27757,
"author_profile": "https://wordpress.stackexchange.com/users/27757",
"pm_score": 0,
"selected": false,
"text": "<p>I define any constants and globals in their own file, and load that both in the main file of the plugin and in <code>uninstall.php</code>. That way all of my globals are organized in a single place. And then I don't have to worry about accidentally performing side-effects on uninstallation, as might happen if using the hook.</p>\n"
}
] |
2015/11/01
|
[
"https://wordpress.stackexchange.com/questions/207261",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66972/"
] |
For activation hooks codex states that you have to be explicit on globals:
[A note on variables during activation](https://codex.wordpress.org/Function_Reference/register_activation_hook#A_Note_on_Variable_Scope)
But that seems not to be working on uninstall.php
If i define a global in my main plugin file like this:
```
global $plugin_options_name;
$plugin_options_name = 'xxxxxxxxx';
```
Activation hook can use it via global statement , whereas uninstall.php cannot.
I have to redeclare the variable inside unistall.php
If this is the case, if i switch to uninstallation hook this will change?
|
You should prefer the uninstall hook over the file if your main plugin doesn't have side effects (outputs html or writes to file/DB automatically when loaded). IMO there is too much risk (i.e. non zero) of doing the uninstall.php code wrong and open the file to direct execution from the outside.
This also help in having all the relevant code in one place.
uninstall.php, when exists, is being executed without loading the plugin code (that is the whole point of it) and therefor whatever is declared in the plugin code will not be available to uninstall.php.
|
207,280 |
<p>I'm using <code>wp_remove_get</code> to get the WordPress theme style content <strong>(style.css)</strong> and then get the theme version number. However I don't know exactly what regex I should use to get the version code:</p>
<pre><code><?php
$response = wp_remote_get( 'http://example.com/wp-content/themes/theme-name/style.css' );
if( is_array($response) ) {
$content = $response['body']; // Remote get the file content. Now get the version number in $content.
}
?>
</code></pre>
<p>Also I'm going to get the version of about 20 themes (sites) on the same page, what I need to do to decrease the page load?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 207263,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": true,
"text": "<p>You should prefer the uninstall hook over the file if your main plugin doesn't have side effects (outputs html or writes to file/DB automatically when loaded). IMO there is too much risk (i.e. non zero) of doing the uninstall.php code wrong and open the file to direct execution from the outside.\nThis also help in having all the relevant code in one place.</p>\n\n<p>uninstall.php, when exists, is being executed without loading the plugin code (that is the whole point of it) and therefor whatever is declared in the plugin code will not be available to uninstall.php.</p>\n"
},
{
"answer_id": 207296,
"author": "J.D.",
"author_id": 27757,
"author_profile": "https://wordpress.stackexchange.com/users/27757",
"pm_score": 0,
"selected": false,
"text": "<p>I define any constants and globals in their own file, and load that both in the main file of the plugin and in <code>uninstall.php</code>. That way all of my globals are organized in a single place. And then I don't have to worry about accidentally performing side-effects on uninstallation, as might happen if using the hook.</p>\n"
}
] |
2015/11/01
|
[
"https://wordpress.stackexchange.com/questions/207280",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82832/"
] |
I'm using `wp_remove_get` to get the WordPress theme style content **(style.css)** and then get the theme version number. However I don't know exactly what regex I should use to get the version code:
```
<?php
$response = wp_remote_get( 'http://example.com/wp-content/themes/theme-name/style.css' );
if( is_array($response) ) {
$content = $response['body']; // Remote get the file content. Now get the version number in $content.
}
?>
```
Also I'm going to get the version of about 20 themes (sites) on the same page, what I need to do to decrease the page load?
Thanks.
|
You should prefer the uninstall hook over the file if your main plugin doesn't have side effects (outputs html or writes to file/DB automatically when loaded). IMO there is too much risk (i.e. non zero) of doing the uninstall.php code wrong and open the file to direct execution from the outside.
This also help in having all the relevant code in one place.
uninstall.php, when exists, is being executed without loading the plugin code (that is the whole point of it) and therefor whatever is declared in the plugin code will not be available to uninstall.php.
|
207,281 |
<p>I am using the code below in a page template.</p>
<p>I have a custom post type of BOOK and there are 2 categories, author and contributor.</p>
<p>My aim is to display the books in author category first, then below these the books in the contributor category.</p>
<p>I think there's a problem with the loop, as the books display fine, but the links don't work. Each of the contributor books displayed take the link from the last book of the author category rather than the one that is associated to itself.</p>
<p>I am using 'amazon_link' to retrieve the custom field of the same name</p>
<p>Any help, much appreciated!</p>
<p>Thanks
Mark</p>
<pre><code><?php
/*
Template Name: Books
*/
?>
<?php get_header(); ?>
<div id="content">
<?php the_post_thumbnail( 'full' ); ?>
<header class="article-header-blue">
<div id="inner-content" class="row">
<div id="main" class="small-12 medium-12 large-12 columns" role="main">
<h1 class="page-title"><?php the_title(); ?></h1>
</div>
</div>
</header> <!-- end article header -->
<div id="inner-content" class="row" data-equalizer>
<?php $loop = new WP_Query( array( 'post_type' => 'books', 'category_name' => 'author', 'posts_per_page' => 12 ) ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="small-12 medium-6 large-4 columns">
<div id="book" data-equalizer-watch>
<a href="<?php echo get_post_meta($post->ID, 'amazon_link', true); ?>" target="_blank">
<?php
// get an image field
$image = get_field('image');
// each image contains a custom field called 'link'
$amazon_link = get_field('amazon_link', $image['ID']);
// render
?>
<a href="<?php echo $amazon_link; ?>" target="_blank">
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" width="200" class="book-img" />
</a>
</a>
<div class="book-container">
<h4 class="book"><a href="<?php echo $amazon_link; ?>" target="_blank"><?php the_title();?></a></h4>
<span class="year-published"><?php echo get_post_meta($post->ID, 'year_published', true); ?></span>
<div class="description-box">
<p class="description"><?php echo get_post_meta($post->ID, 'description', true); ?></p>
</div>
</div>
<a href="<?php echo get_post_meta($post->ID, 'amazon_link', true); ?>" target="blank" title="Buy on Amazon" class="button radius amazon">Buy on Amazon</a>
</div>
</div>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</div>
<div id="inner-content" class="row" data-equalizer>
<h4 class="books">As contributor</h4>
<?php $loop = new WP_Query( array( 'post_type' => 'books', 'category_name' => 'contributor', 'posts_per_page' => 12 ) ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="small-12 medium-6 large-4 columns">
<div id="book" data-equalizer-watch>
<?php
// get an image field
$image = get_field('image');
// each image contains a custom field called 'link'
$link = get_field('amazon_link', $image['ID']);
// render
?>
<a href="<?php echo $amazon_link; ?>" target="_blank">
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" width="200" class="book-img" />
</a>
<div class="book-container">
<h4 class="book"><?php the_title();?></h4>
<span class="year-published"><?php echo get_post_meta($post->ID, 'year_published', true); ?></span>
<div class="description-box">
<p class="description"><?php echo get_post_meta($post->ID, 'description', true); ?></p>
</div>
</div>
<a href="<?php echo get_post_meta($post->ID, 'amazon_link', true); ?>" target="blank" title="Buy on Amazon" class="button radius amazon">Buy on Amazon</a>
</div>
</div>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</div>
</div> <!-- end #content -->
</code></pre>
|
[
{
"answer_id": 207282,
"author": "Macerier",
"author_id": 75321,
"author_profile": "https://wordpress.stackexchange.com/users/75321",
"pm_score": -1,
"selected": false,
"text": "<p>you need to use <code>get_post_meta()</code> not <code>get_field()</code></p>\n"
},
{
"answer_id": 207285,
"author": "Mateusz Hajdziony",
"author_id": 15865,
"author_profile": "https://wordpress.stackexchange.com/users/15865",
"pm_score": 0,
"selected": false,
"text": "<p>The solution is simple: in the first loop, you are setting the <code>$amazon_link</code> like this:</p>\n\n<pre><code>$amazon_link = get_field('amazon_link', $image['ID']);\n</code></pre>\n\n<p>but in the second loop, you are setting a <code>$link</code>, like this:</p>\n\n<pre><code>$link = get_field('amazon_link', $image['ID']);\n</code></pre>\n\n<p>but you're still trying to echo <code>$amazon_link</code> variable later on, which has never been setup in the second loop, so it's value is still the value of the last book from the first loop.</p>\n"
}
] |
2015/11/01
|
[
"https://wordpress.stackexchange.com/questions/207281",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82833/"
] |
I am using the code below in a page template.
I have a custom post type of BOOK and there are 2 categories, author and contributor.
My aim is to display the books in author category first, then below these the books in the contributor category.
I think there's a problem with the loop, as the books display fine, but the links don't work. Each of the contributor books displayed take the link from the last book of the author category rather than the one that is associated to itself.
I am using 'amazon\_link' to retrieve the custom field of the same name
Any help, much appreciated!
Thanks
Mark
```
<?php
/*
Template Name: Books
*/
?>
<?php get_header(); ?>
<div id="content">
<?php the_post_thumbnail( 'full' ); ?>
<header class="article-header-blue">
<div id="inner-content" class="row">
<div id="main" class="small-12 medium-12 large-12 columns" role="main">
<h1 class="page-title"><?php the_title(); ?></h1>
</div>
</div>
</header> <!-- end article header -->
<div id="inner-content" class="row" data-equalizer>
<?php $loop = new WP_Query( array( 'post_type' => 'books', 'category_name' => 'author', 'posts_per_page' => 12 ) ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="small-12 medium-6 large-4 columns">
<div id="book" data-equalizer-watch>
<a href="<?php echo get_post_meta($post->ID, 'amazon_link', true); ?>" target="_blank">
<?php
// get an image field
$image = get_field('image');
// each image contains a custom field called 'link'
$amazon_link = get_field('amazon_link', $image['ID']);
// render
?>
<a href="<?php echo $amazon_link; ?>" target="_blank">
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" width="200" class="book-img" />
</a>
</a>
<div class="book-container">
<h4 class="book"><a href="<?php echo $amazon_link; ?>" target="_blank"><?php the_title();?></a></h4>
<span class="year-published"><?php echo get_post_meta($post->ID, 'year_published', true); ?></span>
<div class="description-box">
<p class="description"><?php echo get_post_meta($post->ID, 'description', true); ?></p>
</div>
</div>
<a href="<?php echo get_post_meta($post->ID, 'amazon_link', true); ?>" target="blank" title="Buy on Amazon" class="button radius amazon">Buy on Amazon</a>
</div>
</div>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</div>
<div id="inner-content" class="row" data-equalizer>
<h4 class="books">As contributor</h4>
<?php $loop = new WP_Query( array( 'post_type' => 'books', 'category_name' => 'contributor', 'posts_per_page' => 12 ) ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="small-12 medium-6 large-4 columns">
<div id="book" data-equalizer-watch>
<?php
// get an image field
$image = get_field('image');
// each image contains a custom field called 'link'
$link = get_field('amazon_link', $image['ID']);
// render
?>
<a href="<?php echo $amazon_link; ?>" target="_blank">
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" width="200" class="book-img" />
</a>
<div class="book-container">
<h4 class="book"><?php the_title();?></h4>
<span class="year-published"><?php echo get_post_meta($post->ID, 'year_published', true); ?></span>
<div class="description-box">
<p class="description"><?php echo get_post_meta($post->ID, 'description', true); ?></p>
</div>
</div>
<a href="<?php echo get_post_meta($post->ID, 'amazon_link', true); ?>" target="blank" title="Buy on Amazon" class="button radius amazon">Buy on Amazon</a>
</div>
</div>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</div>
</div> <!-- end #content -->
```
|
The solution is simple: in the first loop, you are setting the `$amazon_link` like this:
```
$amazon_link = get_field('amazon_link', $image['ID']);
```
but in the second loop, you are setting a `$link`, like this:
```
$link = get_field('amazon_link', $image['ID']);
```
but you're still trying to echo `$amazon_link` variable later on, which has never been setup in the second loop, so it's value is still the value of the last book from the first loop.
|
207,291 |
<p>I have this code to use with shortcode at my portfolio pages.</p>
<p>Everything is working fine, but I need that next and previous get the same category.</p>
<p>This is the code:</p>
<pre><code>add_shortcode( 'prev', 'prev_shortcode' );
add_shortcode( 'next', 'next_shortcode' );
function next_shortcode($atts) {
global $post;
ob_start();
next_post_link( '<div class="nav-next">%link</div>', 'Next project' );
$result = ob_get_contents();
ob_end_clean();
return $result;
}
function prev_shortcode($atts) {
global $post;
ob_start();
previous_post_link( '<div class="nav-previous">%link</div>', 'Previous project' );
$result = ob_get_contents();
ob_end_clean();
return $result;
}
</code></pre>
|
[
{
"answer_id": 207293,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/next_post_link\" rel=\"nofollow\"><code>next_post_link()</code></a> accepts a third argument which will limit the links to the same category. There is an example of this usage in the Codex:</p>\n\n<pre><code>next_post_link( '%link', 'Next post in category', TRUE );\n</code></pre>\n\n<blockquote>\n <p><dl> <dt> in_same_term </dt> <dd> (<i>boolean</i>) (<i>optional</i>) Indicates whether\n next post must be within the same taxonomy term as the current post.\n If set to 'true', only posts from the current taxonomy term\n will be displayed. If the post is in both the parent and subcategory,\n or more than one term, the next post link will lead to the next post\n in any of those terms.</p>\n \n <p><ul> <li> true </li> <li> false </li> </ul> \n Default: false </dd> </dl> </p>\n</blockquote>\n\n<p>What you need, in short, is to add <code>, TRUE</code> to you function arguments:</p>\n\n<pre><code>next_post_link( '<div class=\"nav-next\">%link</div>', 'Next project', TRUE ); \n</code></pre>\n\n<p>And:</p>\n\n<pre><code>previous_post_link( '<div class=\"nav-previous\">%link</div>', 'Previous project', True ); \n</code></pre>\n"
},
{
"answer_id": 207322,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 0,
"selected": false,
"text": "<p>Buffering should always always be used as your last resort, plus one though for trying to return your shortcode output. As you already know, <code>next_post_link()</code> and <code>previous_post_link()</code> echos its results to screen, but we need to return the output from these in order to avoid unexpected output. </p>\n\n<p>These two functions simply echos what is returned from <a href=\"https://developer.wordpress.org/reference/functions/get_next_post_link/\" rel=\"nofollow\"><code>get_next_post_link()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/get_previous_post_link/\" rel=\"nofollow\"><code>get_previous_post_link()</code></a> respectively, so this will be the functions to use in your shortcode</p>\n\n<p>Example:</p>\n\n<pre><code>add_shortcode( 'prev', 'prev_shortcode' );\nadd_shortcode( 'next', 'next_shortcode' );\nfunction next_shortcode() {\n global $post;\n $result = get_next_post_link( '<div class=\"nav-next\">%link</div>', 'Next project' ); \n\n return $result;\n}\n\nfunction prev_shortcode() {\n global $post;\n $result = get_previous_post_link( '<div class=\"nav-previous\">%link</div>', 'Previous project' ); \n\n return $result;\n}\n</code></pre>\n\n<p>I do however have a few concerns here, and that is, why do you need this to run from a shortcode. You are most probably going to use this in a single post page using <code>do_shortcode()</code> to execute the shortcode. You need to remember, shortcodes needs to be parsed, which in turn wastes time and resources (<em>although it might be only a minute amount</em>). Shortcodes should only be used in the page editor's WYSIWYG editor. If you are using shortcodes anywhere but there (<em>that is, using <code>do_shortcode()</code></em>), you are doing it wrong.</p>\n\n<p>You can just simply use <code>next_post_link()</code> and <code>previous_post_link()</code> as is in your template. It is faster and better.</p>\n\n<p>Example:</p>\n\n<pre><code>next_post_link( '<div class=\"nav-next\">%link</div>', 'Next project' ); \nprevious_post_link( '<div class=\"nav-previous\">%link</div>', 'Previous project' ); \n</code></pre>\n\n<p>Apart from what @s_ha_dum has said about setting the third parameter to <code>true</code>, you also need to set the fifth parameter to the taxonomy the terms belongs to if the terms does not belong to the build in taxonomy <code>category</code>. </p>\n\n<p>So, for the build in taxonomy <code>category</code>, you would do</p>\n\n<pre><code>next_post_link( '<div class=\"nav-next\">%link</div>', 'Next project', true ); \nprevious_post_link( '<div class=\"nav-previous\">%link</div>', 'Previous project', true );\n</code></pre>\n\n<p>and for a custom taxonomy, you would do</p>\n\n<pre><code>next_post_link( '<div class=\"nav-next\">%link</div>', 'Next project', true, '', 'MY_TAXONOMY' ); \nprevious_post_link( '<div class=\"nav-previous\">%link</div>', 'Previous project', true, '', 'MY_TAXONOMY' ); \n</code></pre>\n\n<p>where <code>MY_TAXONOMY</code> is the name of your custom taxonomy</p>\n"
}
] |
2015/11/01
|
[
"https://wordpress.stackexchange.com/questions/207291",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82841/"
] |
I have this code to use with shortcode at my portfolio pages.
Everything is working fine, but I need that next and previous get the same category.
This is the code:
```
add_shortcode( 'prev', 'prev_shortcode' );
add_shortcode( 'next', 'next_shortcode' );
function next_shortcode($atts) {
global $post;
ob_start();
next_post_link( '<div class="nav-next">%link</div>', 'Next project' );
$result = ob_get_contents();
ob_end_clean();
return $result;
}
function prev_shortcode($atts) {
global $post;
ob_start();
previous_post_link( '<div class="nav-previous">%link</div>', 'Previous project' );
$result = ob_get_contents();
ob_end_clean();
return $result;
}
```
|
[`next_post_link()`](https://codex.wordpress.org/Function_Reference/next_post_link) accepts a third argument which will limit the links to the same category. There is an example of this usage in the Codex:
```
next_post_link( '%link', 'Next post in category', TRUE );
```
>
> in\_same\_term (*boolean*) (*optional*) Indicates whether
> next post must be within the same taxonomy term as the current post.
> If set to 'true', only posts from the current taxonomy term
> will be displayed. If the post is in both the parent and subcategory,
> or more than one term, the next post link will lead to the next post
> in any of those terms.
>
>
> * true
> * false
>
>
> Default: false
>
>
>
What you need, in short, is to add `, TRUE` to you function arguments:
```
next_post_link( '<div class="nav-next">%link</div>', 'Next project', TRUE );
```
And:
```
previous_post_link( '<div class="nav-previous">%link</div>', 'Previous project', True );
```
|
207,298 |
<p>I am trying to redirect the category link to the first child post. I am using following code in <code>category.php</code>. This redirects, but link doesn't go to first child post. How can I redirect to the first child post, in ASC order by date?</p>
<pre><code>/*
Category Template:
Template URI:
Description:
*/
if ( have_posts() ) :
while ( have_posts() ) : the_post();
wp_redirect( get_permalink( $post->ID ) );
endwhile;
endif;
</code></pre>
|
[
{
"answer_id": 207299,
"author": "flomei",
"author_id": 65455,
"author_profile": "https://wordpress.stackexchange.com/users/65455",
"pm_score": 0,
"selected": false,
"text": "<p>You could probably use <code>get_posts()</code> to refine what you are looking for/where you want to be redirected.</p>\n\n<p>See <a href=\"https://codex.wordpress.org/Template_Tags/get_posts\" rel=\"nofollow\">the Codex for the general use of <code>get_posts()</code> and its parameters</a> and you could use this (untested, hope it works) for your redirect:</p>\n\n<pre><code><?php\n$args = array('posts_per_page' => 1);\n$postslist = get_posts($args);\nforeach ($postslist as $post) :\n setup_postdata($post);\n wp_redirect(the_permalink());\nendforeach; \nwp_reset_postdata();\n?>\n</code></pre>\n"
},
{
"answer_id": 207301,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 3,
"selected": true,
"text": "<p>You are much too late in the page load sequence to redirect. You need to redirect before headers are sent to the browser. The <code>template_redirect</code> hook should be a pretty good option:</p>\n\n<pre><code>function redirect_cat_wpse_207298() {\n if (is_category()) {\n global $post;\n wp_safe_redirect(get_permalink($post->ID));\n die;\n }\n}\nadd_action('template_redirect','redirect_cat_wpse_207298');\n</code></pre>\n"
}
] |
2015/11/01
|
[
"https://wordpress.stackexchange.com/questions/207298",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82846/"
] |
I am trying to redirect the category link to the first child post. I am using following code in `category.php`. This redirects, but link doesn't go to first child post. How can I redirect to the first child post, in ASC order by date?
```
/*
Category Template:
Template URI:
Description:
*/
if ( have_posts() ) :
while ( have_posts() ) : the_post();
wp_redirect( get_permalink( $post->ID ) );
endwhile;
endif;
```
|
You are much too late in the page load sequence to redirect. You need to redirect before headers are sent to the browser. The `template_redirect` hook should be a pretty good option:
```
function redirect_cat_wpse_207298() {
if (is_category()) {
global $post;
wp_safe_redirect(get_permalink($post->ID));
die;
}
}
add_action('template_redirect','redirect_cat_wpse_207298');
```
|
207,334 |
<p>Nowdays a Virus detection plugin is necessary for Wordpress?</p>
<p>EDIT: I mean to prevent attacks and violations... for example i'm using this plugin: <a href="https://sucuri.net/wordpress-security/wordpress-security-monitoring" rel="nofollow">https://sucuri.net/wordpress-security/wordpress-security-monitoring</a> and i recive daily emails about some "Login Failures" using "admin" as Username and some differents passwords from a lot of different IP address.</p>
|
[
{
"answer_id": 207299,
"author": "flomei",
"author_id": 65455,
"author_profile": "https://wordpress.stackexchange.com/users/65455",
"pm_score": 0,
"selected": false,
"text": "<p>You could probably use <code>get_posts()</code> to refine what you are looking for/where you want to be redirected.</p>\n\n<p>See <a href=\"https://codex.wordpress.org/Template_Tags/get_posts\" rel=\"nofollow\">the Codex for the general use of <code>get_posts()</code> and its parameters</a> and you could use this (untested, hope it works) for your redirect:</p>\n\n<pre><code><?php\n$args = array('posts_per_page' => 1);\n$postslist = get_posts($args);\nforeach ($postslist as $post) :\n setup_postdata($post);\n wp_redirect(the_permalink());\nendforeach; \nwp_reset_postdata();\n?>\n</code></pre>\n"
},
{
"answer_id": 207301,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 3,
"selected": true,
"text": "<p>You are much too late in the page load sequence to redirect. You need to redirect before headers are sent to the browser. The <code>template_redirect</code> hook should be a pretty good option:</p>\n\n<pre><code>function redirect_cat_wpse_207298() {\n if (is_category()) {\n global $post;\n wp_safe_redirect(get_permalink($post->ID));\n die;\n }\n}\nadd_action('template_redirect','redirect_cat_wpse_207298');\n</code></pre>\n"
}
] |
2015/11/02
|
[
"https://wordpress.stackexchange.com/questions/207334",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82378/"
] |
Nowdays a Virus detection plugin is necessary for Wordpress?
EDIT: I mean to prevent attacks and violations... for example i'm using this plugin: <https://sucuri.net/wordpress-security/wordpress-security-monitoring> and i recive daily emails about some "Login Failures" using "admin" as Username and some differents passwords from a lot of different IP address.
|
You are much too late in the page load sequence to redirect. You need to redirect before headers are sent to the browser. The `template_redirect` hook should be a pretty good option:
```
function redirect_cat_wpse_207298() {
if (is_category()) {
global $post;
wp_safe_redirect(get_permalink($post->ID));
die;
}
}
add_action('template_redirect','redirect_cat_wpse_207298');
```
|
207,352 |
<p>We all know the advantage of using cdn caching etc.. For that sake i deregistered the script and registered jquery with cdn link . But the problem is that it is showing error like this</p>
<p>Yes Debugging in wordpress is turned on.</p>
<p>It shows error like this .</p>
<blockquote>
<p>Notice: wp_deregister_script was called incorrectly. Do not deregister the jquery script in the administration area. To target the frontend theme, use the wp_enqueue_scripts hook. Please see Debugging in WordPress for more information. (This message was added in version 3.6.) in D:\learnnepal\wp-includes\functions.php on line 3622</p>
</blockquote>
<p>But i think code is fine .</p>
<p>WHen i remove the following lines of code that notice don't show ?</p>
<pre><code>add_action( 'wp_enqueue_scripts', function(){
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', array(), null, false );
wp_enqueue_script( 'jquery');
});
</code></pre>
<p>Is there any problem with the code?</p>
<p>Clearly turning off debugging is workaround but very bad practise isn't it?</p>
|
[
{
"answer_id": 207353,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 3,
"selected": true,
"text": "<p>Based on the error...</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', function(){\n if (is_admin()) return; // don't dequeue on the backend\n wp_deregister_script( 'jquery' );\n wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', array(), null, false );\n wp_enqueue_script( 'jquery');\n});\n</code></pre>\n\n<p>Honestly, unless you have tremendous traffic over a broad geographic area, I'd say that CDNs are grossly over-rated. I've watched the hangup on sites I've managed and very often the bottleneck is the CDN-- I'm looking at you Google. So, this may not be a solution worth implementing. </p>\n\n<p>Second, dequeueing Core scripts is a dangerous game. Plugins and themes depend upon those scripts. If you load a different version than the one expected scripts can fail.</p>\n\n<blockquote>\n <p>Clearly turning off debugging is workaround but very bad practise\n isn't it?</p>\n</blockquote>\n\n<p>Production or development? Debugging should be off on a production server and turned on only while debugging. </p>\n"
},
{
"answer_id": 207354,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 2,
"selected": false,
"text": "<p>As the error notes, you really don't want to <code>deregister the jquery script in the administration area</code>. What you could do to avoid the notice:</p>\n\n<pre><code>if ( ! is_admin() ) {\n add_action( 'wp_enqueue_scripts', function(){\n wp_deregister_script( 'jquery' );\n wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', array(), null, false );\n wp_enqueue_script( 'jquery');\n });\n}\n</code></pre>\n\n<p>The reason you shouldn't do the deregister in the admin area is that a lot of the WP core functionality for the admin section is reliant on JavaScript, and the WP team has coded that functionality to work specifically with the version of jQuery that ships with WordPress. While there shouldn't be any difference in functionality, if there was something missing or broken in a different jQuery version it could render your admin area unusable.</p>\n"
},
{
"answer_id": 207360,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 1,
"selected": false,
"text": "<p>If you use the right hook then it shouldn't complain:</p>\n\n<pre><code>if ( is_admin() ) {\n $hook = 'admin_enqueue_scripts';\n} elseif ( 'wp-login.php' === $GLOBALS['pagenow'] ) {\n $hook = 'login_enqueue_scripts';\n} else {\n $hook = 'wp_enqueue_scripts';\n}\nadd_action( $hook, function() {\n wp_deregister_script( 'jquery' );\n wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', array(), null, false );\n wp_enqueue_script( 'jquery');\n} );\n</code></pre>\n"
}
] |
2015/11/02
|
[
"https://wordpress.stackexchange.com/questions/207352",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82119/"
] |
We all know the advantage of using cdn caching etc.. For that sake i deregistered the script and registered jquery with cdn link . But the problem is that it is showing error like this
Yes Debugging in wordpress is turned on.
It shows error like this .
>
> Notice: wp\_deregister\_script was called incorrectly. Do not deregister the jquery script in the administration area. To target the frontend theme, use the wp\_enqueue\_scripts hook. Please see Debugging in WordPress for more information. (This message was added in version 3.6.) in D:\learnnepal\wp-includes\functions.php on line 3622
>
>
>
But i think code is fine .
WHen i remove the following lines of code that notice don't show ?
```
add_action( 'wp_enqueue_scripts', function(){
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', array(), null, false );
wp_enqueue_script( 'jquery');
});
```
Is there any problem with the code?
Clearly turning off debugging is workaround but very bad practise isn't it?
|
Based on the error...
```
add_action( 'wp_enqueue_scripts', function(){
if (is_admin()) return; // don't dequeue on the backend
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', array(), null, false );
wp_enqueue_script( 'jquery');
});
```
Honestly, unless you have tremendous traffic over a broad geographic area, I'd say that CDNs are grossly over-rated. I've watched the hangup on sites I've managed and very often the bottleneck is the CDN-- I'm looking at you Google. So, this may not be a solution worth implementing.
Second, dequeueing Core scripts is a dangerous game. Plugins and themes depend upon those scripts. If you load a different version than the one expected scripts can fail.
>
> Clearly turning off debugging is workaround but very bad practise
> isn't it?
>
>
>
Production or development? Debugging should be off on a production server and turned on only while debugging.
|
207,365 |
<p>yesterday @jas helped to how to show archive by years in my nav. It works fine, but there is the second one little problem.</p>
<p>The @jas's solution filter me posts from all categories by year, I'd need to add filter to just one category.</p>
<p>The function which add me years to my navigation is:</p>
<pre><code>add_filter( 'wp_nav_menu_objects', 'ravs_add_menu_parent_class' );
function ravs_add_menu_parent_class( $items ) {
foreach ( $items as $item ) {
//print_r($item);//print each menu item an get your parent menu item-id
// get your menu item ID use that ID in below code and you can remove this code after getting ID
}
GLOBAL $wpdb;
$years = $wpdb->get_results( "SELECT YEAR(post_date) AS year FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' GROUP BY year DESC" );
foreach($years as $year){
$link = array (
'title' => $year->year,
// 'title' =>($year->year == date('Y') ) ? 'News (Category)' : $year->year, // this is how you want to print latest year as "News (Category)"
'menu_item_parent' => '13', // my menu id is 13 ie: ID of menu name test under which years links are displayed
'ID' => '',
'db_id' => '',
'url' => '/'.$year->year // to create url of menu item
);
$items[] = (object) $link;
}
return $items;
}
</code></pre>
<p>Is there someone who helps me to extend it to category 'news' (if ID is needed, the cat's ID is '4').</p>
<p>Thanks for all.<br>
Roman</p>
|
[
{
"answer_id": 207368,
"author": "stlawrance",
"author_id": 82119,
"author_profile": "https://wordpress.stackexchange.com/users/82119",
"pm_score": 0,
"selected": false,
"text": "<p>I cannot comment so sorry .\nWhy don't you try using WP_QUERY . </p>\n\n<p>You can learn about WP_Query either from codex or personally i like tutsplus mastering wp_query.</p>\n\n<p><a href=\"http://code.tutsplus.com/tutorials/mastering-wp_query-an-introduction--cms-23023\" rel=\"nofollow\">http://code.tutsplus.com/tutorials/mastering-wp_query-an-introduction--cms-23023</a></p>\n\n<p>You are using $wpdb to fetch data from database. But i think it is probably not the best way although it works :)</p>\n"
},
{
"answer_id": 207370,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 2,
"selected": true,
"text": "<p>If I understand you question clearly that we just need to get post in that submenus from only cat id = 4 , this will make your archive.php to work only for cat id = 4</p>\n\n<p>Please add below code to <strong>functions.php</strong>:</p>\n\n<pre><code>function wpse75668_filter_pre_get_posts( $query ) {\n\n\n if ( $query->is_main_query() && ! is_admin() ) {\n\n if ( is_date() ) {\n\n $query->set( 'cat', '4' );\n }\n }\n }\n add_action( 'pre_get_posts', 'wpse75668_filter_pre_get_posts' );\n</code></pre>\n\n<p>Thanks!</p>\n"
}
] |
2015/11/02
|
[
"https://wordpress.stackexchange.com/questions/207365",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82177/"
] |
yesterday @jas helped to how to show archive by years in my nav. It works fine, but there is the second one little problem.
The @jas's solution filter me posts from all categories by year, I'd need to add filter to just one category.
The function which add me years to my navigation is:
```
add_filter( 'wp_nav_menu_objects', 'ravs_add_menu_parent_class' );
function ravs_add_menu_parent_class( $items ) {
foreach ( $items as $item ) {
//print_r($item);//print each menu item an get your parent menu item-id
// get your menu item ID use that ID in below code and you can remove this code after getting ID
}
GLOBAL $wpdb;
$years = $wpdb->get_results( "SELECT YEAR(post_date) AS year FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' GROUP BY year DESC" );
foreach($years as $year){
$link = array (
'title' => $year->year,
// 'title' =>($year->year == date('Y') ) ? 'News (Category)' : $year->year, // this is how you want to print latest year as "News (Category)"
'menu_item_parent' => '13', // my menu id is 13 ie: ID of menu name test under which years links are displayed
'ID' => '',
'db_id' => '',
'url' => '/'.$year->year // to create url of menu item
);
$items[] = (object) $link;
}
return $items;
}
```
Is there someone who helps me to extend it to category 'news' (if ID is needed, the cat's ID is '4').
Thanks for all.
Roman
|
If I understand you question clearly that we just need to get post in that submenus from only cat id = 4 , this will make your archive.php to work only for cat id = 4
Please add below code to **functions.php**:
```
function wpse75668_filter_pre_get_posts( $query ) {
if ( $query->is_main_query() && ! is_admin() ) {
if ( is_date() ) {
$query->set( 'cat', '4' );
}
}
}
add_action( 'pre_get_posts', 'wpse75668_filter_pre_get_posts' );
```
Thanks!
|
207,383 |
<p>I am trying to run the following query to access my WP cf7dbplugin_submits table but it keeps coming up empty. I have added my table into wp-db.php model as such:</p>
<pre><code>Added the contact form table- cf7dbplugin_submits to the following at about line 268:
var $tables = array('cf7dbplugin_submits','posts', . . .)
At around line 304 add the following:
/**
* WordPress cf7dbplugin_submits table
*/
public $cf7dbplugin_submits;
</code></pre>
<p>So the database function should find it (it has when used elsewhere in my code). But the following is consistently coming up empty for any $postid:</p>
<pre><code>function action_getpost($postid) {
global $wpdb, $out;
$out['post'] = array();
$out['uploads'] = array();
// wp_posts has one row for each submitted form.
// wp_nf_objectmeta includes a set of rows for each defined form.
$query =
"SELECT submit_time, form_name, field_value" .
"FROM $wpdb->cf7dbplugin_submits " .
"WHERE field_order = %d AND submit_time = %d ";
$queryp = $wpdb->prepare($query, array(9999, $postid));
if (empty($queryp)) {
$out['errmsg'] = "Internal error: \"$query\" \"$postid\"";
return;
}
$wpdb->show_errors( true );
$row = $wpdb->get_row($queryp, ARRAY_A);
if (empty($row)) {
$out['errmsg'] = "No rows matching: \"$postid\"";
return;
}
</code></pre>
<p>If I just run the following query in phpMyAdmin, where $postid = 1445125066.4375:</p>
<pre><code>SELECT submit_time, form_name, field_value
FROM wp_cf7dbplugin_submits
WHERE field_order = 9999 AND submit_time = 1445125066.4375
</code></pre>
<p>It produces the needed row </p>
<pre><code>submit_time form_name field_value
1445125066.4375 Demographics usernamehere
</code></pre>
<p>So why is the function returning my error of no rows matching 1445125066.4375? Any ideas?</p>
|
[
{
"answer_id": 207368,
"author": "stlawrance",
"author_id": 82119,
"author_profile": "https://wordpress.stackexchange.com/users/82119",
"pm_score": 0,
"selected": false,
"text": "<p>I cannot comment so sorry .\nWhy don't you try using WP_QUERY . </p>\n\n<p>You can learn about WP_Query either from codex or personally i like tutsplus mastering wp_query.</p>\n\n<p><a href=\"http://code.tutsplus.com/tutorials/mastering-wp_query-an-introduction--cms-23023\" rel=\"nofollow\">http://code.tutsplus.com/tutorials/mastering-wp_query-an-introduction--cms-23023</a></p>\n\n<p>You are using $wpdb to fetch data from database. But i think it is probably not the best way although it works :)</p>\n"
},
{
"answer_id": 207370,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 2,
"selected": true,
"text": "<p>If I understand you question clearly that we just need to get post in that submenus from only cat id = 4 , this will make your archive.php to work only for cat id = 4</p>\n\n<p>Please add below code to <strong>functions.php</strong>:</p>\n\n<pre><code>function wpse75668_filter_pre_get_posts( $query ) {\n\n\n if ( $query->is_main_query() && ! is_admin() ) {\n\n if ( is_date() ) {\n\n $query->set( 'cat', '4' );\n }\n }\n }\n add_action( 'pre_get_posts', 'wpse75668_filter_pre_get_posts' );\n</code></pre>\n\n<p>Thanks!</p>\n"
}
] |
2015/11/02
|
[
"https://wordpress.stackexchange.com/questions/207383",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82889/"
] |
I am trying to run the following query to access my WP cf7dbplugin\_submits table but it keeps coming up empty. I have added my table into wp-db.php model as such:
```
Added the contact form table- cf7dbplugin_submits to the following at about line 268:
var $tables = array('cf7dbplugin_submits','posts', . . .)
At around line 304 add the following:
/**
* WordPress cf7dbplugin_submits table
*/
public $cf7dbplugin_submits;
```
So the database function should find it (it has when used elsewhere in my code). But the following is consistently coming up empty for any $postid:
```
function action_getpost($postid) {
global $wpdb, $out;
$out['post'] = array();
$out['uploads'] = array();
// wp_posts has one row for each submitted form.
// wp_nf_objectmeta includes a set of rows for each defined form.
$query =
"SELECT submit_time, form_name, field_value" .
"FROM $wpdb->cf7dbplugin_submits " .
"WHERE field_order = %d AND submit_time = %d ";
$queryp = $wpdb->prepare($query, array(9999, $postid));
if (empty($queryp)) {
$out['errmsg'] = "Internal error: \"$query\" \"$postid\"";
return;
}
$wpdb->show_errors( true );
$row = $wpdb->get_row($queryp, ARRAY_A);
if (empty($row)) {
$out['errmsg'] = "No rows matching: \"$postid\"";
return;
}
```
If I just run the following query in phpMyAdmin, where $postid = 1445125066.4375:
```
SELECT submit_time, form_name, field_value
FROM wp_cf7dbplugin_submits
WHERE field_order = 9999 AND submit_time = 1445125066.4375
```
It produces the needed row
```
submit_time form_name field_value
1445125066.4375 Demographics usernamehere
```
So why is the function returning my error of no rows matching 1445125066.4375? Any ideas?
|
If I understand you question clearly that we just need to get post in that submenus from only cat id = 4 , this will make your archive.php to work only for cat id = 4
Please add below code to **functions.php**:
```
function wpse75668_filter_pre_get_posts( $query ) {
if ( $query->is_main_query() && ! is_admin() ) {
if ( is_date() ) {
$query->set( 'cat', '4' );
}
}
}
add_action( 'pre_get_posts', 'wpse75668_filter_pre_get_posts' );
```
Thanks!
|
207,405 |
<p>I was wondering if it's possible to convert this kind of shortcode:</p>
<pre><code>[card name="Muscle Band" set="XY" no="121" c="name"][/card]
</code></pre>
<p>Into this in Visual Mode (in blue-colored text):</p>
<blockquote>
<p>Muscle Band XY 121</p>
</blockquote>
<p>Basically, something that detects shortcode that's in the above format and changes it into the second format only when you look at it in Visual mode (the card name, set, and number).</p>
<p>Thank you!</p>
|
[
{
"answer_id": 207368,
"author": "stlawrance",
"author_id": 82119,
"author_profile": "https://wordpress.stackexchange.com/users/82119",
"pm_score": 0,
"selected": false,
"text": "<p>I cannot comment so sorry .\nWhy don't you try using WP_QUERY . </p>\n\n<p>You can learn about WP_Query either from codex or personally i like tutsplus mastering wp_query.</p>\n\n<p><a href=\"http://code.tutsplus.com/tutorials/mastering-wp_query-an-introduction--cms-23023\" rel=\"nofollow\">http://code.tutsplus.com/tutorials/mastering-wp_query-an-introduction--cms-23023</a></p>\n\n<p>You are using $wpdb to fetch data from database. But i think it is probably not the best way although it works :)</p>\n"
},
{
"answer_id": 207370,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 2,
"selected": true,
"text": "<p>If I understand you question clearly that we just need to get post in that submenus from only cat id = 4 , this will make your archive.php to work only for cat id = 4</p>\n\n<p>Please add below code to <strong>functions.php</strong>:</p>\n\n<pre><code>function wpse75668_filter_pre_get_posts( $query ) {\n\n\n if ( $query->is_main_query() && ! is_admin() ) {\n\n if ( is_date() ) {\n\n $query->set( 'cat', '4' );\n }\n }\n }\n add_action( 'pre_get_posts', 'wpse75668_filter_pre_get_posts' );\n</code></pre>\n\n<p>Thanks!</p>\n"
}
] |
2015/11/03
|
[
"https://wordpress.stackexchange.com/questions/207405",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34465/"
] |
I was wondering if it's possible to convert this kind of shortcode:
```
[card name="Muscle Band" set="XY" no="121" c="name"][/card]
```
Into this in Visual Mode (in blue-colored text):
>
> Muscle Band XY 121
>
>
>
Basically, something that detects shortcode that's in the above format and changes it into the second format only when you look at it in Visual mode (the card name, set, and number).
Thank you!
|
If I understand you question clearly that we just need to get post in that submenus from only cat id = 4 , this will make your archive.php to work only for cat id = 4
Please add below code to **functions.php**:
```
function wpse75668_filter_pre_get_posts( $query ) {
if ( $query->is_main_query() && ! is_admin() ) {
if ( is_date() ) {
$query->set( 'cat', '4' );
}
}
}
add_action( 'pre_get_posts', 'wpse75668_filter_pre_get_posts' );
```
Thanks!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.