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
|
---|---|---|---|---|---|---|
194,326 |
<p>I'm trying to import a database and wonder how I can stop getting the following error?</p>
<blockquote>
<p>"#1075 - Incorrect table definition; there can be only one auto column
and it must be defined as a key "</p>
</blockquote>
<p>Here's the result when importing using PHPMyAdmin.</p>
<p>SQL query:</p>
<pre><code>--
-- Database: `db_factorypattern`
--
-- --------------------------------------------------------
--
-- Table structure for table `wp_commentmeta`
--
CREATE TABLE IF NOT EXISTS `wp_commentmeta` (
`meta_id` bigint(20) unsigned NOT NULL auto_increment,
`comment_id` bigint(20) unsigned NOT NULL default '0',
`meta_key` varchar(255) default NULL,
`meta_value` longtext
) ENGINE=MyISAM AUTO_INCREMENT=2610 DEFAULT CHARSET=utf8;
</code></pre>
<p>MySQL said: Documentation</p>
<blockquote>
<p>"#1075 - Incorrect table definition; there can be only one auto column
and it must be defined as a key "</p>
</blockquote>
|
[
{
"answer_id": 194340,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": false,
"text": "<p>I am not sure where you got that export code but I don't see the <code>PRIMARY KEY</code> defined as it should be. Take a look at the <a href=\"https://core.trac.wordpress.org/browser/trunk/src/wp-admin/includes/schema.php#L87\" rel=\"nofollow\">code from Core that creates the table</a>:</p>\n\n<pre><code>87 CREATE TABLE $wpdb->commentmeta (\n88 meta_id bigint(20) unsigned NOT NULL auto_increment,\n89 comment_id bigint(20) unsigned NOT NULL default '0',\n90 meta_key varchar(255) default NULL,\n91 meta_value longtext,\n92 PRIMARY KEY (meta_id),\n93 KEY comment_id (comment_id),\n94 KEY meta_key (meta_key($max_index_length))\n95 ) $charset_collate;\n</code></pre>\n\n<p>Take a look at line 92. That is missing from your \"create\" statement. </p>\n"
},
{
"answer_id": 276281,
"author": "Yunax Technologies",
"author_id": 125528,
"author_profile": "https://wordpress.stackexchange.com/users/125528",
"pm_score": 0,
"selected": false,
"text": "<p>This technique worked for me</p>\n\n<ol>\n<li><p>Click the \"Export\" tab for the database</p></li>\n<li><p>Click the \"Custom\" radio button</p></li>\n<li><p>Go the section titled \"Format-specific options\" and change the dropdown for \"Database system or older MySQL server to maximize output compatibility with:\" from NONE to MYSQL40.</p></li>\n<li><p>Scroll to the bottom and click \"GO\".</p></li>\n</ol>\n\n<p>I'm not certain if doing this causes any data loss, however in the one time I've tried it I did not notice any. Neither did anyone who responded in the forums linked to above.</p>\n"
}
] |
2015/07/13
|
[
"https://wordpress.stackexchange.com/questions/194326",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76109/"
] |
I'm trying to import a database and wonder how I can stop getting the following error?
>
> "#1075 - Incorrect table definition; there can be only one auto column
> and it must be defined as a key "
>
>
>
Here's the result when importing using PHPMyAdmin.
SQL query:
```
--
-- Database: `db_factorypattern`
--
-- --------------------------------------------------------
--
-- Table structure for table `wp_commentmeta`
--
CREATE TABLE IF NOT EXISTS `wp_commentmeta` (
`meta_id` bigint(20) unsigned NOT NULL auto_increment,
`comment_id` bigint(20) unsigned NOT NULL default '0',
`meta_key` varchar(255) default NULL,
`meta_value` longtext
) ENGINE=MyISAM AUTO_INCREMENT=2610 DEFAULT CHARSET=utf8;
```
MySQL said: Documentation
>
> "#1075 - Incorrect table definition; there can be only one auto column
> and it must be defined as a key "
>
>
>
|
I am not sure where you got that export code but I don't see the `PRIMARY KEY` defined as it should be. Take a look at the [code from Core that creates the table](https://core.trac.wordpress.org/browser/trunk/src/wp-admin/includes/schema.php#L87):
```
87 CREATE TABLE $wpdb->commentmeta (
88 meta_id bigint(20) unsigned NOT NULL auto_increment,
89 comment_id bigint(20) unsigned NOT NULL default '0',
90 meta_key varchar(255) default NULL,
91 meta_value longtext,
92 PRIMARY KEY (meta_id),
93 KEY comment_id (comment_id),
94 KEY meta_key (meta_key($max_index_length))
95 ) $charset_collate;
```
Take a look at line 92. That is missing from your "create" statement.
|
194,348 |
<p>I'd like to intercept 404 errors and do some things before to show the 404 error page.</p>
<p>How can intercept the 404 error?</p>
|
[
{
"answer_id": 194384,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 6,
"selected": true,
"text": "<p>As was mentioned in a comment, <code>template_redirect</code> would be an appropriate hook for intercepting a 404 before the template is loaded.</p>\n\n<pre><code>function wpd_do_stuff_on_404(){\n if( is_404() ){\n // do stuff\n }\n}\nadd_action( 'template_redirect', 'wpd_do_stuff_on_404' );\n</code></pre>\n\n<p>Refer to the <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"noreferrer\">Action Reference</a> for the general order of actions on the front end. The main query runs between the <code>posts_selection</code> and <code>wp</code> actions, so that is the earliest you can determine that a request is a 404. The template is then loaded after <code>template_redirect</code>, so it's too late to set headers after that point.</p>\n"
},
{
"answer_id": 194416,
"author": "Kushal Shah",
"author_id": 64076,
"author_profile": "https://wordpress.stackexchange.com/users/64076",
"pm_score": -1,
"selected": false,
"text": "<p>Using below code you can directly redirect on home page when 404 call, please remove all code from the 404.php file and add below code.</p>\n\n<pre><code><?php\nheader(\"HTTP/1.1 301 Moved Permanently\");\nheader(\"Location: \".get_bloginfo('url'));\nexit();\n?>\n</code></pre>\n"
}
] |
2015/07/13
|
[
"https://wordpress.stackexchange.com/questions/194348",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57145/"
] |
I'd like to intercept 404 errors and do some things before to show the 404 error page.
How can intercept the 404 error?
|
As was mentioned in a comment, `template_redirect` would be an appropriate hook for intercepting a 404 before the template is loaded.
```
function wpd_do_stuff_on_404(){
if( is_404() ){
// do stuff
}
}
add_action( 'template_redirect', 'wpd_do_stuff_on_404' );
```
Refer to the [Action Reference](http://codex.wordpress.org/Plugin_API/Action_Reference) for the general order of actions on the front end. The main query runs between the `posts_selection` and `wp` actions, so that is the earliest you can determine that a request is a 404. The template is then loaded after `template_redirect`, so it's too late to set headers after that point.
|
194,352 |
<p>All I'm trying to do here is a simple custom loop using WP_Query to display posts if they are published in the last 24 hours; otherwise, a message appears telling the user to check back soon for fresh posts. I'm trying to use the date_query parameter in my arguments but I'm getting unexpected results...at first it will work, but if I check the page in a few minutes, its as if it reset itself... my loop is set up below:</p>
<pre><code>$args = array(
'post_type' => 'surf_reports',
'posts_per_page' => '1',
'category_name' => $cat (this is pulled dynamically in my template),
'date_query' => array(
'before' => strtotime('-24 hours')
)
);
</code></pre>
<p>And then obviously below there would be a loop, I'm not going to share that bc its standard and I believe unrelated to the issue. </p>
|
[
{
"answer_id": 194365,
"author": "terminator",
"author_id": 55034,
"author_profile": "https://wordpress.stackexchange.com/users/55034",
"pm_score": 4,
"selected": true,
"text": "<p>As birgire said date query is an array of arrays \nMay be this solves your problemo. </p>\n\n<pre><code>$args = array(\n 'post_type' => 'surf_reports',\n 'posts_per_page' => '1',\n 'category_name' => $cat (this is pulled dynamically in my template),\n 'date_query' => array(\n array(\n 'after' => '24 hours ago'\n )\n )\n );\n</code></pre>\n"
},
{
"answer_id": 194397,
"author": "Brad Dalton",
"author_id": 9884,
"author_profile": "https://wordpress.stackexchange.com/users/9884",
"pm_score": 0,
"selected": false,
"text": "<p><strong>before</strong> (string/array) - Date to retrieve posts before. Accepts strtotime()-compatible string, or array of 'year', 'month', 'day' values:</p>\n\n<p>I would try the before parameter with a value of 1 day or 24 hours</p>\n"
}
] |
2015/07/13
|
[
"https://wordpress.stackexchange.com/questions/194352",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/55073/"
] |
All I'm trying to do here is a simple custom loop using WP\_Query to display posts if they are published in the last 24 hours; otherwise, a message appears telling the user to check back soon for fresh posts. I'm trying to use the date\_query parameter in my arguments but I'm getting unexpected results...at first it will work, but if I check the page in a few minutes, its as if it reset itself... my loop is set up below:
```
$args = array(
'post_type' => 'surf_reports',
'posts_per_page' => '1',
'category_name' => $cat (this is pulled dynamically in my template),
'date_query' => array(
'before' => strtotime('-24 hours')
)
);
```
And then obviously below there would be a loop, I'm not going to share that bc its standard and I believe unrelated to the issue.
|
As birgire said date query is an array of arrays
May be this solves your problemo.
```
$args = array(
'post_type' => 'surf_reports',
'posts_per_page' => '1',
'category_name' => $cat (this is pulled dynamically in my template),
'date_query' => array(
array(
'after' => '24 hours ago'
)
)
);
```
|
194,363 |
<p>I have more than 500 posts and I want to limit only 100 posts with pagination. So, 10 pages with 10 posts in each.
Presenting you the code:</p>
<pre><code>$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$posts = get_posts(
array(
'numberposts' => 10,
'paged' => $paged,
'meta_key' => 'property',
'orderby' => 'meta_value_num', //or 'meta_value_num'
'order' => 'DESC',
)
);
if( $posts ) {
$count = 0;
foreach( $posts as $post ) {
setup_postdata( $post );
// post stuff
$count++;
}
wp_reset_postdata();
}
</code></pre>
|
[
{
"answer_id": 194368,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>Before I start, do not use <code>get_posts</code> for paginated queries. <code>get_posts</code> legally breaks pagination, and does not return the query object. If you need to paginate queries, use <code>WP_Query</code></p>\n\n<p>As for your issue, I really don't think limiting the total overall amount of posts to only 100 is possible when you involve pagination. The only scenarios I can think of is: </p>\n\n<ul>\n<li><p>Remove the page links on page 10, but again you can manually enter page 11 and see page 11 posts</p></li>\n<li><p>Run a custom function when a new post is published to change the post status of 101st post and sequencial posts to something else, like <code>draft</code>. By default, <code>WP_Query</code> only queries <code>publish</code>ed posts for all users and extra <code>private</code> posts for logged in users. So if you change post status, these posts will be excluded</p></li>\n<li><p>Another, less intrusive method will be to run two queries. The first one, which will be very basic and lean, will return the post ID's <strong>only</strong> of the first 100 posts. This ID's will be passed to the second query which will get 10 posts per page and have only 10 pages because we just pass 100 ID's to it. The advantage here is, if you manually enter page 11, you'll get a 404 page. </p></li>\n</ul>\n\n<h2>EXAMPLE OF POINT 3</h2>\n\n<p>As I have said, point 3 is the best option here. We will use <code>get_posts</code> for the first query as it cuts out pagination, which speeds up your query, and we will only get the post ID's which makes the complete query 99.9% faster than normal. Overall, the impact on the page is nearly zero. For our second query we will use <code>WP_Query</code> and the <code>post__in</code> parameter to get our paged list of posts</p>\n\n<p>(<em>This code is untested and requires PHP 5.4+</em>)</p>\n\n<pre><code>$args = [\n 'posts_per_page' => 100,\n 'fields' => 'ids',\n // Add additional args here\n];\n$post_ids = get_posts( $args );\n\nif ( $post_ids ) {\n $args_2 = [\n 'paged' => $paged,\n 'post__in' => $post_ids,\n 'posts_per_page' => 10,\n ];\n $q = new WP_Query( $args_2 );\n while ( $q->have_posts() ) {\n $q->the_post();\n // YOUR LOOP\n }\n next_posts_link( 'Next Posts', $q->max_num_pages );\n previous_posts_link( 'Previous Posts' ); \n wp_reset_postdata();\n}\n</code></pre>\n"
},
{
"answer_id": 194402,
"author": "Anand",
"author_id": 73187,
"author_profile": "https://wordpress.stackexchange.com/users/73187",
"pm_score": 0,
"selected": false,
"text": "<p>Try this code that will helps you display only 10 pages.</p>\n\n<p>This is code where you want to display the post:</p>\n\n<pre><code><?php \n$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n$args = array( 'post_type' => 'property', 'posts_per_page' => 10,'paged'=> $paged,'orderby'=> 'meta_value_num','order'=> 'DESC');\n$loop = new WP_Query( $args );\nwhile ( $loop->have_posts() ) : $loop->the_post();\nprint_r($post); ?>\n<h1> <?php the_post_thumbnail(); ?></h1>\n<h2><?php the_title(); ?></h2>\n<h3><?php the_content(); ?></h3>\n<?php endwhile; ?>\n</code></pre>\n\n<p>This is footer where you need to display pagination.</p>\n\n<pre><code><?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; ?>\n<?php if($loop->max_num_pages > 1 && $loop->max_num_pages < 11 ) { ?>\n<ul class=\"pager\">\n<?php for($i=1;$i<=$loop->max_num_pages; $i++){ ?>\n<li><a href=\"<?php get_permalink();?>page/<?php echo $i; ?>\"> <?php echo $i; ?></a></li>\n<?php } ?>\n</ul>\n<?php } else if($loop->max_num_pages > 1 && $loop->max_num_pages > 10) { ?>\n<ul class=\"pager\">\n<?php for($i=1;$i<=10; $i++){ ?>\n<li><a href=\"<?php get_permalink();?>page/<?php echo $i; ?>\"> <?php echo $i; ?></a></li>\n<?php } ?>\n</ul>\n<?php } else{ ?>\n\n<?php } ?>\n</code></pre>\n"
},
{
"answer_id": 194403,
"author": "Trang",
"author_id": 70868,
"author_profile": "https://wordpress.stackexchange.com/users/70868",
"pm_score": 3,
"selected": false,
"text": "<p>Maybe it helps</p>\n\n<pre><code>function wpcodex_filter_main_search_post_limits( $limit, $query ) { \n return 'LIMIT 0, 100'; \n} \nadd_filter( 'post_limits', 'wpcodex_filter_main_search_post_limits', 10, 2 );\n</code></pre>\n\n<p>More: <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/post_limits\" rel=\"noreferrer\"><code>post_limits</code> filter</a></p>\n"
}
] |
2015/07/13
|
[
"https://wordpress.stackexchange.com/questions/194363",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/36035/"
] |
I have more than 500 posts and I want to limit only 100 posts with pagination. So, 10 pages with 10 posts in each.
Presenting you the code:
```
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$posts = get_posts(
array(
'numberposts' => 10,
'paged' => $paged,
'meta_key' => 'property',
'orderby' => 'meta_value_num', //or 'meta_value_num'
'order' => 'DESC',
)
);
if( $posts ) {
$count = 0;
foreach( $posts as $post ) {
setup_postdata( $post );
// post stuff
$count++;
}
wp_reset_postdata();
}
```
|
Before I start, do not use `get_posts` for paginated queries. `get_posts` legally breaks pagination, and does not return the query object. If you need to paginate queries, use `WP_Query`
As for your issue, I really don't think limiting the total overall amount of posts to only 100 is possible when you involve pagination. The only scenarios I can think of is:
* Remove the page links on page 10, but again you can manually enter page 11 and see page 11 posts
* Run a custom function when a new post is published to change the post status of 101st post and sequencial posts to something else, like `draft`. By default, `WP_Query` only queries `publish`ed posts for all users and extra `private` posts for logged in users. So if you change post status, these posts will be excluded
* Another, less intrusive method will be to run two queries. The first one, which will be very basic and lean, will return the post ID's **only** of the first 100 posts. This ID's will be passed to the second query which will get 10 posts per page and have only 10 pages because we just pass 100 ID's to it. The advantage here is, if you manually enter page 11, you'll get a 404 page.
EXAMPLE OF POINT 3
------------------
As I have said, point 3 is the best option here. We will use `get_posts` for the first query as it cuts out pagination, which speeds up your query, and we will only get the post ID's which makes the complete query 99.9% faster than normal. Overall, the impact on the page is nearly zero. For our second query we will use `WP_Query` and the `post__in` parameter to get our paged list of posts
(*This code is untested and requires PHP 5.4+*)
```
$args = [
'posts_per_page' => 100,
'fields' => 'ids',
// Add additional args here
];
$post_ids = get_posts( $args );
if ( $post_ids ) {
$args_2 = [
'paged' => $paged,
'post__in' => $post_ids,
'posts_per_page' => 10,
];
$q = new WP_Query( $args_2 );
while ( $q->have_posts() ) {
$q->the_post();
// YOUR LOOP
}
next_posts_link( 'Next Posts', $q->max_num_pages );
previous_posts_link( 'Previous Posts' );
wp_reset_postdata();
}
```
|
194,374 |
<h2>History:</h2>
<p>I'm working on a project for a client that involves building 27 unique websites that are built on wordpress. I say unique, because (for reasons that are not worth going into here) they aren't and can't be installed in a multi-site environment. Each of these sites will have the same theme installed and one or two custom plugins as well. I can't use the WordPress theme directory, because the theme is specifically built for my client and won't work for just any application (the same goes for the plugins). So this brings me to my question...</p>
<h2>Question:</h2>
<p>Is there any solution out there for hosting and automatically updating private themes and plugins? And if the answer to that is no, are there suggestions as to how to begin building something like that?</p>
|
[
{
"answer_id": 194368,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>Before I start, do not use <code>get_posts</code> for paginated queries. <code>get_posts</code> legally breaks pagination, and does not return the query object. If you need to paginate queries, use <code>WP_Query</code></p>\n\n<p>As for your issue, I really don't think limiting the total overall amount of posts to only 100 is possible when you involve pagination. The only scenarios I can think of is: </p>\n\n<ul>\n<li><p>Remove the page links on page 10, but again you can manually enter page 11 and see page 11 posts</p></li>\n<li><p>Run a custom function when a new post is published to change the post status of 101st post and sequencial posts to something else, like <code>draft</code>. By default, <code>WP_Query</code> only queries <code>publish</code>ed posts for all users and extra <code>private</code> posts for logged in users. So if you change post status, these posts will be excluded</p></li>\n<li><p>Another, less intrusive method will be to run two queries. The first one, which will be very basic and lean, will return the post ID's <strong>only</strong> of the first 100 posts. This ID's will be passed to the second query which will get 10 posts per page and have only 10 pages because we just pass 100 ID's to it. The advantage here is, if you manually enter page 11, you'll get a 404 page. </p></li>\n</ul>\n\n<h2>EXAMPLE OF POINT 3</h2>\n\n<p>As I have said, point 3 is the best option here. We will use <code>get_posts</code> for the first query as it cuts out pagination, which speeds up your query, and we will only get the post ID's which makes the complete query 99.9% faster than normal. Overall, the impact on the page is nearly zero. For our second query we will use <code>WP_Query</code> and the <code>post__in</code> parameter to get our paged list of posts</p>\n\n<p>(<em>This code is untested and requires PHP 5.4+</em>)</p>\n\n<pre><code>$args = [\n 'posts_per_page' => 100,\n 'fields' => 'ids',\n // Add additional args here\n];\n$post_ids = get_posts( $args );\n\nif ( $post_ids ) {\n $args_2 = [\n 'paged' => $paged,\n 'post__in' => $post_ids,\n 'posts_per_page' => 10,\n ];\n $q = new WP_Query( $args_2 );\n while ( $q->have_posts() ) {\n $q->the_post();\n // YOUR LOOP\n }\n next_posts_link( 'Next Posts', $q->max_num_pages );\n previous_posts_link( 'Previous Posts' ); \n wp_reset_postdata();\n}\n</code></pre>\n"
},
{
"answer_id": 194402,
"author": "Anand",
"author_id": 73187,
"author_profile": "https://wordpress.stackexchange.com/users/73187",
"pm_score": 0,
"selected": false,
"text": "<p>Try this code that will helps you display only 10 pages.</p>\n\n<p>This is code where you want to display the post:</p>\n\n<pre><code><?php \n$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n$args = array( 'post_type' => 'property', 'posts_per_page' => 10,'paged'=> $paged,'orderby'=> 'meta_value_num','order'=> 'DESC');\n$loop = new WP_Query( $args );\nwhile ( $loop->have_posts() ) : $loop->the_post();\nprint_r($post); ?>\n<h1> <?php the_post_thumbnail(); ?></h1>\n<h2><?php the_title(); ?></h2>\n<h3><?php the_content(); ?></h3>\n<?php endwhile; ?>\n</code></pre>\n\n<p>This is footer where you need to display pagination.</p>\n\n<pre><code><?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; ?>\n<?php if($loop->max_num_pages > 1 && $loop->max_num_pages < 11 ) { ?>\n<ul class=\"pager\">\n<?php for($i=1;$i<=$loop->max_num_pages; $i++){ ?>\n<li><a href=\"<?php get_permalink();?>page/<?php echo $i; ?>\"> <?php echo $i; ?></a></li>\n<?php } ?>\n</ul>\n<?php } else if($loop->max_num_pages > 1 && $loop->max_num_pages > 10) { ?>\n<ul class=\"pager\">\n<?php for($i=1;$i<=10; $i++){ ?>\n<li><a href=\"<?php get_permalink();?>page/<?php echo $i; ?>\"> <?php echo $i; ?></a></li>\n<?php } ?>\n</ul>\n<?php } else{ ?>\n\n<?php } ?>\n</code></pre>\n"
},
{
"answer_id": 194403,
"author": "Trang",
"author_id": 70868,
"author_profile": "https://wordpress.stackexchange.com/users/70868",
"pm_score": 3,
"selected": false,
"text": "<p>Maybe it helps</p>\n\n<pre><code>function wpcodex_filter_main_search_post_limits( $limit, $query ) { \n return 'LIMIT 0, 100'; \n} \nadd_filter( 'post_limits', 'wpcodex_filter_main_search_post_limits', 10, 2 );\n</code></pre>\n\n<p>More: <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/post_limits\" rel=\"noreferrer\"><code>post_limits</code> filter</a></p>\n"
}
] |
2015/07/13
|
[
"https://wordpress.stackexchange.com/questions/194374",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/15404/"
] |
History:
--------
I'm working on a project for a client that involves building 27 unique websites that are built on wordpress. I say unique, because (for reasons that are not worth going into here) they aren't and can't be installed in a multi-site environment. Each of these sites will have the same theme installed and one or two custom plugins as well. I can't use the WordPress theme directory, because the theme is specifically built for my client and won't work for just any application (the same goes for the plugins). So this brings me to my question...
Question:
---------
Is there any solution out there for hosting and automatically updating private themes and plugins? And if the answer to that is no, are there suggestions as to how to begin building something like that?
|
Before I start, do not use `get_posts` for paginated queries. `get_posts` legally breaks pagination, and does not return the query object. If you need to paginate queries, use `WP_Query`
As for your issue, I really don't think limiting the total overall amount of posts to only 100 is possible when you involve pagination. The only scenarios I can think of is:
* Remove the page links on page 10, but again you can manually enter page 11 and see page 11 posts
* Run a custom function when a new post is published to change the post status of 101st post and sequencial posts to something else, like `draft`. By default, `WP_Query` only queries `publish`ed posts for all users and extra `private` posts for logged in users. So if you change post status, these posts will be excluded
* Another, less intrusive method will be to run two queries. The first one, which will be very basic and lean, will return the post ID's **only** of the first 100 posts. This ID's will be passed to the second query which will get 10 posts per page and have only 10 pages because we just pass 100 ID's to it. The advantage here is, if you manually enter page 11, you'll get a 404 page.
EXAMPLE OF POINT 3
------------------
As I have said, point 3 is the best option here. We will use `get_posts` for the first query as it cuts out pagination, which speeds up your query, and we will only get the post ID's which makes the complete query 99.9% faster than normal. Overall, the impact on the page is nearly zero. For our second query we will use `WP_Query` and the `post__in` parameter to get our paged list of posts
(*This code is untested and requires PHP 5.4+*)
```
$args = [
'posts_per_page' => 100,
'fields' => 'ids',
// Add additional args here
];
$post_ids = get_posts( $args );
if ( $post_ids ) {
$args_2 = [
'paged' => $paged,
'post__in' => $post_ids,
'posts_per_page' => 10,
];
$q = new WP_Query( $args_2 );
while ( $q->have_posts() ) {
$q->the_post();
// YOUR LOOP
}
next_posts_link( 'Next Posts', $q->max_num_pages );
previous_posts_link( 'Previous Posts' );
wp_reset_postdata();
}
```
|
194,385 |
<p>I'm working on a plugin that seems to be fine in Chrome, but is not firing the PHP script via Ajax in Firefox. It is driving me to distraction. Here are the code blocks that relate to it.</p>
<p>First, the JavaScript enqueue:</p>
<pre><code>wp_enqueue_script ( 'jquery' );
$script_url = plugins_url ( '/js/seamless-donations.js', __FILE__ );
wp_register_script ( 'seamless_javascript_code', $script_url, array( 'jquery' ), false );
wp_enqueue_script ( 'seamless_javascript_code' );
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script (
'seamless_javascript_code', 'dgxDonateAjax',
array(
'ajaxurl' => admin_url ( 'admin-ajax.php' ),
'nonce' => wp_create_nonce ( 'dgx-donate-nonce' ),
'postalCodeRequired' => dgx_donate_get_countries_requiring_postal_code ()
)
);
</code></pre>
<p>Now, the related JavaScript that makes the Ajax call:</p>
<pre><code>console.log("-- SeamlessDonationsCheckout: before jQuery.post");
console.log("-- SeamlessDonationsCheckout: ajaxurl=" + dgxDonateAjax.ajaxurl);
jQuery.ajax({
url: dgxDonateAjax.ajaxurl,
data: data,
success: function() {
console.log("-- SeamlessDonationsCheckout: jQuery.ajax success");
//response(data);
}
});
//jQuery.post(dgxDonateAjax.ajaxurl, data, SeamlessDonationsAjaxCallback);
console.log("-- SeamlessDonationsCheckout: after jQuery.post");
</code></pre>
<p>The data array consists of:</p>
<pre><code>var data = {
action: 'dgx_donate_paypalstd_ajax_checkout',
referringUrl: referringUrl,
nonce: nonce,
sessionID: sessionID,
donationAmount: donationAmount,
(and so on, it's a large array)
};
</code></pre>
<p>The hooks:</p>
<pre><code>add_action ( 'wp_ajax_dgx_donate_paypalstd_ajax_checkout', 'dgx_donate_paypalstd_ajax_checkout' );
add_action ( 'wp_ajax_nopriv_dgx_donate_paypalstd_ajax_checkout', 'dgx_donate_paypalstd_ajax_checkout' );
</code></pre>
<p>And, finally, the beginning of the PHP Ajax function:</p>
<pre><code>function dgx_donate_paypalstd_ajax_checkout () {
// Log
dgx_donate_debug_log ( '----------------------------------------' );
dgx_donate_debug_log ( 'DONATION TRANSACTION STARTED' );
$php_version = phpversion ();
dgx_donate_debug_log ( "PHP Version: $php_version" );
dgx_donate_debug_log ( "Seamless Donations Version: " . dgx_donate_get_version () );
</code></pre>
<p>In Chrome, the log file clearly shows the function has been called, but there's nothing in Firefox. Also, in Chrome, the browser log shows the log entries before and after the jQuery.ajax calls, as well as the "success" entry, but Firefox does not.</p>
<p>I can confirm that the variable for the Ajax URL is passed, because this message </p>
<pre><code>"-- SeamlessDonationsCheckout: ajaxurl=http://podtrack.com/wp-admin/admin-ajax.php"
</code></pre>
<p>shows in the Firefox browser console. So it's not like the ajax URL isn't being passed along.</p>
<p>I would sure appreciate any guidance. This one has had me very stumped.</p>
<p>Thanks!</p>
<p>--David</p>
|
[
{
"answer_id": 194488,
"author": "voldemortensen",
"author_id": 76192,
"author_profile": "https://wordpress.stackexchange.com/users/76192",
"pm_score": 0,
"selected": false,
"text": "<p>You need\n <code>type: 'POST'</code>\nin your jQuery.ajax call. The default is GET, and this requires POST.</p>\n\n<p>Because someone below requested an example:</p>\n\n<pre><code>jQuery.ajax({\n url: dgxDonateAjax.ajaxurl,\n data: data,\n type: 'POST',\n success: function() {\n console.log(\"-- SeamlessDonationsCheckout: jQuery.ajax success\");\n //response(data);\n }\n});\n</code></pre>\n"
},
{
"answer_id": 212034,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 1,
"selected": false,
"text": "<p>This is the barebones for an AJAX call and response. Take a look and make sure this is working on Chrome and Firefox for you -- works for me.</p>\n\n<pre><code><?php\n\n// Some function for data we'll pass\n\nfunction dgx_donate_get_countries_requiring_postal_code()\n{\n return \"cc postal code stuff...\";\n}\n\n// Register everything\n\nadd_action('init', function () {\n\n // Add required scripts\n\n wp_enqueue_script('jquery');\n $script_url = plugins_url('/js/seamless-donations.js', __FILE__);\n\n wp_register_script('seamless_javascript_code', $script_url, array('jquery'), false);\n wp_enqueue_script('seamless_javascript_code');\n\n // Localize our data \n\n wp_localize_script(\n 'seamless_javascript_code', 'dgxDonateAjax',\n array(\n 'ajaxurl' => admin_url('admin-ajax.php'),\n 'nonce' => wp_create_nonce('dgx-donate-nonce'),\n 'postalCodeRequired' => dgx_donate_get_countries_requiring_postal_code()\n )\n );\n\n // Register AJAX handlers\n\n add_action('wp_ajax_dgx_donate_paypalstd_ajax_checkout', 'dgx_donate_paypalstd_ajax_checkout');\n add_action('wp_ajax_nopriv_dgx_donate_paypalstd_ajax_checkout', 'dgx_donate_paypalstd_ajax_checkout');\n\n // AJAX handler (PRIV / NO PRIV)\n\n function dgx_donate_paypalstd_ajax_checkout()\n {\n // If we fail don't be silent \n\n $fail_message = '';\n\n if (empty($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'dgx-donate-nonce')) $fail_message = 'Bad Nonce';\n if (empty ($_POST['action'])) $fail_message = 'Missing Action';\n if ($_POST['action'] !== 'dgx_donate_paypalstd_ajax_checkout') $fail_message = 'Bad Action';\n\n // We failed, let em know...\n\n if (!empty ($fail_message)) {\n wp_send_json_error(array(\n 'message' => $fail_message\n )); // die\n }\n\n // Do logic stuff\n\n // Send the Success Response\n\n wp_send_json_success(array(\n 'action' => $_POST['action'],\n 'message' => 'Checkout Complete',\n 'postalCodeRequired' => $_POST['postalCodeRequired'],\n 'ID' => 1\n )); // die\n }\n});\n\n// Shortcut to trigger AJAX call on page load\n\nadd_action('wp_footer', function () { ?>\n\n <script>\n\n (function ($) {\n\n var data = {\n action: 'dgx_donate_paypalstd_ajax_checkout',\n nonce: dgxDonateAjax.nonce,\n postalCodeRequired: dgxDonateAjax.postalCodeRequired,\n };\n\n $.ajax({\n type: 'POST',\n url: dgxDonateAjax.ajaxurl,\n data: data,\n success: function (response) {\n\n // look at the response \n\n if (response.success) {\n\n // succcess data\n console.log(response.data);\n\n } else {\n\n // no good\n console.log(response);\n }\n }\n });\n\n })(jQuery);\n </script>\n<?php });\n</code></pre>\n"
}
] |
2015/07/13
|
[
"https://wordpress.stackexchange.com/questions/194385",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75753/"
] |
I'm working on a plugin that seems to be fine in Chrome, but is not firing the PHP script via Ajax in Firefox. It is driving me to distraction. Here are the code blocks that relate to it.
First, the JavaScript enqueue:
```
wp_enqueue_script ( 'jquery' );
$script_url = plugins_url ( '/js/seamless-donations.js', __FILE__ );
wp_register_script ( 'seamless_javascript_code', $script_url, array( 'jquery' ), false );
wp_enqueue_script ( 'seamless_javascript_code' );
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script (
'seamless_javascript_code', 'dgxDonateAjax',
array(
'ajaxurl' => admin_url ( 'admin-ajax.php' ),
'nonce' => wp_create_nonce ( 'dgx-donate-nonce' ),
'postalCodeRequired' => dgx_donate_get_countries_requiring_postal_code ()
)
);
```
Now, the related JavaScript that makes the Ajax call:
```
console.log("-- SeamlessDonationsCheckout: before jQuery.post");
console.log("-- SeamlessDonationsCheckout: ajaxurl=" + dgxDonateAjax.ajaxurl);
jQuery.ajax({
url: dgxDonateAjax.ajaxurl,
data: data,
success: function() {
console.log("-- SeamlessDonationsCheckout: jQuery.ajax success");
//response(data);
}
});
//jQuery.post(dgxDonateAjax.ajaxurl, data, SeamlessDonationsAjaxCallback);
console.log("-- SeamlessDonationsCheckout: after jQuery.post");
```
The data array consists of:
```
var data = {
action: 'dgx_donate_paypalstd_ajax_checkout',
referringUrl: referringUrl,
nonce: nonce,
sessionID: sessionID,
donationAmount: donationAmount,
(and so on, it's a large array)
};
```
The hooks:
```
add_action ( 'wp_ajax_dgx_donate_paypalstd_ajax_checkout', 'dgx_donate_paypalstd_ajax_checkout' );
add_action ( 'wp_ajax_nopriv_dgx_donate_paypalstd_ajax_checkout', 'dgx_donate_paypalstd_ajax_checkout' );
```
And, finally, the beginning of the PHP Ajax function:
```
function dgx_donate_paypalstd_ajax_checkout () {
// Log
dgx_donate_debug_log ( '----------------------------------------' );
dgx_donate_debug_log ( 'DONATION TRANSACTION STARTED' );
$php_version = phpversion ();
dgx_donate_debug_log ( "PHP Version: $php_version" );
dgx_donate_debug_log ( "Seamless Donations Version: " . dgx_donate_get_version () );
```
In Chrome, the log file clearly shows the function has been called, but there's nothing in Firefox. Also, in Chrome, the browser log shows the log entries before and after the jQuery.ajax calls, as well as the "success" entry, but Firefox does not.
I can confirm that the variable for the Ajax URL is passed, because this message
```
"-- SeamlessDonationsCheckout: ajaxurl=http://podtrack.com/wp-admin/admin-ajax.php"
```
shows in the Firefox browser console. So it's not like the ajax URL isn't being passed along.
I would sure appreciate any guidance. This one has had me very stumped.
Thanks!
--David
|
This is the barebones for an AJAX call and response. Take a look and make sure this is working on Chrome and Firefox for you -- works for me.
```
<?php
// Some function for data we'll pass
function dgx_donate_get_countries_requiring_postal_code()
{
return "cc postal code stuff...";
}
// Register everything
add_action('init', function () {
// Add required scripts
wp_enqueue_script('jquery');
$script_url = plugins_url('/js/seamless-donations.js', __FILE__);
wp_register_script('seamless_javascript_code', $script_url, array('jquery'), false);
wp_enqueue_script('seamless_javascript_code');
// Localize our data
wp_localize_script(
'seamless_javascript_code', 'dgxDonateAjax',
array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('dgx-donate-nonce'),
'postalCodeRequired' => dgx_donate_get_countries_requiring_postal_code()
)
);
// Register AJAX handlers
add_action('wp_ajax_dgx_donate_paypalstd_ajax_checkout', 'dgx_donate_paypalstd_ajax_checkout');
add_action('wp_ajax_nopriv_dgx_donate_paypalstd_ajax_checkout', 'dgx_donate_paypalstd_ajax_checkout');
// AJAX handler (PRIV / NO PRIV)
function dgx_donate_paypalstd_ajax_checkout()
{
// If we fail don't be silent
$fail_message = '';
if (empty($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'dgx-donate-nonce')) $fail_message = 'Bad Nonce';
if (empty ($_POST['action'])) $fail_message = 'Missing Action';
if ($_POST['action'] !== 'dgx_donate_paypalstd_ajax_checkout') $fail_message = 'Bad Action';
// We failed, let em know...
if (!empty ($fail_message)) {
wp_send_json_error(array(
'message' => $fail_message
)); // die
}
// Do logic stuff
// Send the Success Response
wp_send_json_success(array(
'action' => $_POST['action'],
'message' => 'Checkout Complete',
'postalCodeRequired' => $_POST['postalCodeRequired'],
'ID' => 1
)); // die
}
});
// Shortcut to trigger AJAX call on page load
add_action('wp_footer', function () { ?>
<script>
(function ($) {
var data = {
action: 'dgx_donate_paypalstd_ajax_checkout',
nonce: dgxDonateAjax.nonce,
postalCodeRequired: dgxDonateAjax.postalCodeRequired,
};
$.ajax({
type: 'POST',
url: dgxDonateAjax.ajaxurl,
data: data,
success: function (response) {
// look at the response
if (response.success) {
// succcess data
console.log(response.data);
} else {
// no good
console.log(response);
}
}
});
})(jQuery);
</script>
<?php });
```
|
194,417 |
<p>I have created a custom post types in function.php file.</p>
<p>I has created 4 categories on Service menu section, aa, bb, cc and dd, I try to get a latest 5 post for specific category but I can archive this.</p>
<p>this is my query post:</p>
<pre><code>query_posts(array('showposts' => 5, 'post_type' => array('servicios'), 'cat' => 14));
</code></pre>
<p>14 is the id for category <em>aa</em> for example, I has tried <em>Tag_ID</em>, <em>category_name</em> and <em>term</em> instead <em>cat</em> and not work. What's wrong in my query?</p>
<p>UPDATE:</p>
<p>These are my argument right now:</p>
<pre><code>$args = array(
'paged' => 1,
'posts_per_page' => '5',
'offset' => 0,
'post_status' => 'publish',
'ignore_sticky_posts' => 0,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => array (
'servicios' => 'servicios',
),
'cat' => '15'
);
</code></pre>
<p>this is my generated sql query of wp_query: </p>
<pre><code>SELECT SQL_CALC_FOUND_ROWS mt24xi_posts.ID FROM mt24xi_posts
INNER JOIN mt24xi_term_relationships ON (mt24xi_posts.ID = mt24xi_term_relationships.object_id) WHERE 1=1
AND ( mt24xi_term_relationships.term_taxonomy_id IN (12) )
AND mt24xi_posts.post_type IN ('post', 'page')
AND (mt24xi_posts.post_status = 'publish' OR mt24xi_posts.post_author = 1
AND mt24xi_posts.post_status = 'private')
GROUP BY mt24xi_posts.ID ORDER BY mt24xi_posts.post_date DESC LIMIT 0, 5
</code></pre>
<p>If I remove "AND mt24xi_posts.post_type IN ('post', 'page')" the query work fine</p>
|
[
{
"answer_id": 194420,
"author": "Brad Dalton",
"author_id": 9884,
"author_profile": "https://wordpress.stackexchange.com/users/9884",
"pm_score": 0,
"selected": false,
"text": "<p>Don't use <a href=\"https://wordpress.stackexchange.com/questions/50761/when-to-use-wp-query-query-posts-and-pre-get-posts\"><code>query_posts</code></a></p>\n\n<p>Create a new <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\"><code>WP_Query</code></a> or use pre_get_posts to modify an existing query.</p>\n\n<pre><code>$args = array(\n 'post_type' => 'servicios',\n 'category_name' => 'category-name'\n);\n$the_query = new WP_Query( $args );\n\n// The Loop\nif ( $the_query->have_posts() ) {\n echo '<ul>';\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n echo '<li>' . get_the_title() . '</li>';\n }\n echo '</ul>';\n} else {\n // no posts found\n}\n/* Restore original Post Data */\nwp_reset_postdata();\n</code></pre>\n\n<p>Swap out category-name with the name of your category.</p>\n"
},
{
"answer_id": 194508,
"author": "xzegga",
"author_id": 75093,
"author_profile": "https://wordpress.stackexchange.com/users/75093",
"pm_score": 2,
"selected": true,
"text": "<p>After two days with this problem have resolved the problem, I fix it adding tax_query parameter with my taxonomy name and slug of the category requested:</p>\n\n<pre><code>$args = array(\n 'post_type' => array (\n 'servicios' => 'servicios',\n ),\n 'tax_query' => array(\n array(\n 'taxonomy' => 'category',\n 'field' => 'slug',\n 'terms' => 'dgit'\n )\n )\n);\n</code></pre>\n"
}
] |
2015/07/14
|
[
"https://wordpress.stackexchange.com/questions/194417",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75093/"
] |
I have created a custom post types in function.php file.
I has created 4 categories on Service menu section, aa, bb, cc and dd, I try to get a latest 5 post for specific category but I can archive this.
this is my query post:
```
query_posts(array('showposts' => 5, 'post_type' => array('servicios'), 'cat' => 14));
```
14 is the id for category *aa* for example, I has tried *Tag\_ID*, *category\_name* and *term* instead *cat* and not work. What's wrong in my query?
UPDATE:
These are my argument right now:
```
$args = array(
'paged' => 1,
'posts_per_page' => '5',
'offset' => 0,
'post_status' => 'publish',
'ignore_sticky_posts' => 0,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => array (
'servicios' => 'servicios',
),
'cat' => '15'
);
```
this is my generated sql query of wp\_query:
```
SELECT SQL_CALC_FOUND_ROWS mt24xi_posts.ID FROM mt24xi_posts
INNER JOIN mt24xi_term_relationships ON (mt24xi_posts.ID = mt24xi_term_relationships.object_id) WHERE 1=1
AND ( mt24xi_term_relationships.term_taxonomy_id IN (12) )
AND mt24xi_posts.post_type IN ('post', 'page')
AND (mt24xi_posts.post_status = 'publish' OR mt24xi_posts.post_author = 1
AND mt24xi_posts.post_status = 'private')
GROUP BY mt24xi_posts.ID ORDER BY mt24xi_posts.post_date DESC LIMIT 0, 5
```
If I remove "AND mt24xi\_posts.post\_type IN ('post', 'page')" the query work fine
|
After two days with this problem have resolved the problem, I fix it adding tax\_query parameter with my taxonomy name and slug of the category requested:
```
$args = array(
'post_type' => array (
'servicios' => 'servicios',
),
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'dgit'
)
)
);
```
|
194,439 |
<p>I have posts with very different post lengths. </p>
<p>Sometimes there are very long posts, sometimes a very short comment on a book. </p>
<p>I have set my excerpt length to 50 words, but when a post is 25 words long, the "Read more" link doesn't show up. </p>
<p>Any ideas?</p>
|
[
{
"answer_id": 194452,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p>The reason is the <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/formatting.php#L2676-L2682\" rel=\"nofollow\">following check</a> in the <code>wp_trim_words()</code> function:</p>\n\n<pre><code>if ( count( $words_array ) > $num_words ) {\n array_pop( $words_array );\n $text = implode( $sep, $words_array );\n $text = $text . $more;\n} else {\n $text = implode( $sep, $words_array );\n}\n</code></pre>\n\n<p>You can therefore try the following:</p>\n\n<pre><code>add_filter( 'wp_trim_words', function( $text, $num_words, $more ) {\n return $more === mb_substr( $text, -1 * mb_strlen( $more ) ) ? $text : $text . $more;\n}, 11, 3 );\n</code></pre>\n\n<p>to append the <code>$more</code> link to the <code>$text</code>, if it's missing.</p>\n\n<p>But I think your readers might be disappointent when they click the link on short posts and discover there's nothing new to read ;-)</p>\n"
},
{
"answer_id": 194464,
"author": "giraff",
"author_id": 63967,
"author_profile": "https://wordpress.stackexchange.com/users/63967",
"pm_score": -1,
"selected": false,
"text": "<p>I had a similar problem and solved it by:</p>\n\n<ul>\n<li><p>disabling the readmore link</p>\n\n<pre><code>add_filter( 'the_content_more_link', 'modify_read_more_link' );\nfunction modify_read_more_link() {\n return '';\n}\n</code></pre></li>\n<li><p>adding the link in the template</p></li>\n</ul>\n\n<pre>\necho '<a class=\"more-link\" href=\"' . get_permalink() . '\">Read more...';\n</pre>\n"
},
{
"answer_id": 194514,
"author": "Jawad Satti",
"author_id": 76208,
"author_profile": "https://wordpress.stackexchange.com/users/76208",
"pm_score": 0,
"selected": false,
"text": "<p>I use the <a href=\"https://wordpress.org/plugins/post-teaser/\" rel=\"nofollow\">Post Teaser</a> plugin on my site. Just install and set how many words you want to show on the page; a link underneath opens the full post. </p>\n"
}
] |
2015/07/14
|
[
"https://wordpress.stackexchange.com/questions/194439",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76166/"
] |
I have posts with very different post lengths.
Sometimes there are very long posts, sometimes a very short comment on a book.
I have set my excerpt length to 50 words, but when a post is 25 words long, the "Read more" link doesn't show up.
Any ideas?
|
The reason is the [following check](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/formatting.php#L2676-L2682) in the `wp_trim_words()` function:
```
if ( count( $words_array ) > $num_words ) {
array_pop( $words_array );
$text = implode( $sep, $words_array );
$text = $text . $more;
} else {
$text = implode( $sep, $words_array );
}
```
You can therefore try the following:
```
add_filter( 'wp_trim_words', function( $text, $num_words, $more ) {
return $more === mb_substr( $text, -1 * mb_strlen( $more ) ) ? $text : $text . $more;
}, 11, 3 );
```
to append the `$more` link to the `$text`, if it's missing.
But I think your readers might be disappointent when they click the link on short posts and discover there's nothing new to read ;-)
|
194,444 |
<p>I have custom field in posts called <em>hex_colors</em> which contains hex color codes separated with white space, custom field value is like this:</p>
<pre><code>"000000 f0f0f0 c0c0c0 202020 404040 "
</code></pre>
<p>I can change function which create it to separate with ", " or " | " or anything else, if it helps.</p>
<p>I can show it like this:</p>
<pre><code><?php
if (get_custom_field('hex_colors')) {
echo '<div>'; echo get_custom_field('hex_colors'); echo '</div>';
}
?>
</code></pre>
<p>But I would like to show each color code one by one and to style each one, for example instead of this:</p>
<pre><code><div>000000 f0f0f0 c0c0c0 202020 404040</div>
</code></pre>
<p>to get something like this:</p>
<pre><code><div class="colors" style="background-color:#000000">000000</div>
<div class="colors" style="background-color:#f0f0f0">f0f0f0</div>
<div class="colors" style="background-color:#c0c0c0">c0c0c0</div>
<div class="colors" style="background-color:#202020">202020</div>
<div class="colors" style="background-color:#404040">404040</div>
</code></pre>
<hr>
<pre><code>I tried like this:
if ( get_post_meta( get_the_ID(), 'hex_colors', true ) ){
$colors = get_post_meta( get_the_ID(), 'hex_colors', true );
$colors = explode( ' ' , $colors );
foreach( $colors as $color ) {
echo '<div>';
echo $color;
echo '</div>';
}
}
</code></pre>
<p>It works, but I get output something like this:</p>
<pre><code><div>000000</div>
<div></div>
<div>f0f0f0</div>
<div></div>
<div>c0c0c0</div>
<div></div>
<div>c0c0c0</div>
<div></div>
<div>404040</div>
<div></div>
</code></pre>
<p>Empty div () at the end (because of " " white space at the end of custom field value.
This is function which create custom filed:</p>
<pre><code><?php
for ($i = 0; $i < $colors_to_show; $i += $inc) {
for($j=0;$j<$inc;$j++) {
$out_color_text .= ''.$colors_key[$i + $j].' '; // CUSTOM FIELD VALUE
}
}
$id = $post->ID; // Post ID
$value = $out_color_text;
add_post_meta($id, 'hex_colors', $value, true);
?>
</code></pre>
<p>Some fix to create value without white space at the end?</p>
|
[
{
"answer_id": 194452,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p>The reason is the <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/formatting.php#L2676-L2682\" rel=\"nofollow\">following check</a> in the <code>wp_trim_words()</code> function:</p>\n\n<pre><code>if ( count( $words_array ) > $num_words ) {\n array_pop( $words_array );\n $text = implode( $sep, $words_array );\n $text = $text . $more;\n} else {\n $text = implode( $sep, $words_array );\n}\n</code></pre>\n\n<p>You can therefore try the following:</p>\n\n<pre><code>add_filter( 'wp_trim_words', function( $text, $num_words, $more ) {\n return $more === mb_substr( $text, -1 * mb_strlen( $more ) ) ? $text : $text . $more;\n}, 11, 3 );\n</code></pre>\n\n<p>to append the <code>$more</code> link to the <code>$text</code>, if it's missing.</p>\n\n<p>But I think your readers might be disappointent when they click the link on short posts and discover there's nothing new to read ;-)</p>\n"
},
{
"answer_id": 194464,
"author": "giraff",
"author_id": 63967,
"author_profile": "https://wordpress.stackexchange.com/users/63967",
"pm_score": -1,
"selected": false,
"text": "<p>I had a similar problem and solved it by:</p>\n\n<ul>\n<li><p>disabling the readmore link</p>\n\n<pre><code>add_filter( 'the_content_more_link', 'modify_read_more_link' );\nfunction modify_read_more_link() {\n return '';\n}\n</code></pre></li>\n<li><p>adding the link in the template</p></li>\n</ul>\n\n<pre>\necho '<a class=\"more-link\" href=\"' . get_permalink() . '\">Read more...';\n</pre>\n"
},
{
"answer_id": 194514,
"author": "Jawad Satti",
"author_id": 76208,
"author_profile": "https://wordpress.stackexchange.com/users/76208",
"pm_score": 0,
"selected": false,
"text": "<p>I use the <a href=\"https://wordpress.org/plugins/post-teaser/\" rel=\"nofollow\">Post Teaser</a> plugin on my site. Just install and set how many words you want to show on the page; a link underneath opens the full post. </p>\n"
}
] |
2015/07/14
|
[
"https://wordpress.stackexchange.com/questions/194444",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25053/"
] |
I have custom field in posts called *hex\_colors* which contains hex color codes separated with white space, custom field value is like this:
```
"000000 f0f0f0 c0c0c0 202020 404040 "
```
I can change function which create it to separate with ", " or " | " or anything else, if it helps.
I can show it like this:
```
<?php
if (get_custom_field('hex_colors')) {
echo '<div>'; echo get_custom_field('hex_colors'); echo '</div>';
}
?>
```
But I would like to show each color code one by one and to style each one, for example instead of this:
```
<div>000000 f0f0f0 c0c0c0 202020 404040</div>
```
to get something like this:
```
<div class="colors" style="background-color:#000000">000000</div>
<div class="colors" style="background-color:#f0f0f0">f0f0f0</div>
<div class="colors" style="background-color:#c0c0c0">c0c0c0</div>
<div class="colors" style="background-color:#202020">202020</div>
<div class="colors" style="background-color:#404040">404040</div>
```
---
```
I tried like this:
if ( get_post_meta( get_the_ID(), 'hex_colors', true ) ){
$colors = get_post_meta( get_the_ID(), 'hex_colors', true );
$colors = explode( ' ' , $colors );
foreach( $colors as $color ) {
echo '<div>';
echo $color;
echo '</div>';
}
}
```
It works, but I get output something like this:
```
<div>000000</div>
<div></div>
<div>f0f0f0</div>
<div></div>
<div>c0c0c0</div>
<div></div>
<div>c0c0c0</div>
<div></div>
<div>404040</div>
<div></div>
```
Empty div () at the end (because of " " white space at the end of custom field value.
This is function which create custom filed:
```
<?php
for ($i = 0; $i < $colors_to_show; $i += $inc) {
for($j=0;$j<$inc;$j++) {
$out_color_text .= ''.$colors_key[$i + $j].' '; // CUSTOM FIELD VALUE
}
}
$id = $post->ID; // Post ID
$value = $out_color_text;
add_post_meta($id, 'hex_colors', $value, true);
?>
```
Some fix to create value without white space at the end?
|
The reason is the [following check](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/formatting.php#L2676-L2682) in the `wp_trim_words()` function:
```
if ( count( $words_array ) > $num_words ) {
array_pop( $words_array );
$text = implode( $sep, $words_array );
$text = $text . $more;
} else {
$text = implode( $sep, $words_array );
}
```
You can therefore try the following:
```
add_filter( 'wp_trim_words', function( $text, $num_words, $more ) {
return $more === mb_substr( $text, -1 * mb_strlen( $more ) ) ? $text : $text . $more;
}, 11, 3 );
```
to append the `$more` link to the `$text`, if it's missing.
But I think your readers might be disappointent when they click the link on short posts and discover there's nothing new to read ;-)
|
194,446 |
<p>I have a running Wordpress site (3.9.6). Now a new theme should be used and for this theme also some customizations have to be made (content, some WP files like page.php and so on). Additionally, I have to update to Wordpress 4. All changes shouldn't be noticed by visitors or at least as small as possible. Before the site goes live also an editor should get access to edit and add content.</p>
<p>I think this should happen very often and I want to know how do you do that.</p>
<ul>
<li>Should a completely new WP site be set up? Should this be done locally or in a subdirectory of the server?</li>
<li>Is it possible to work
live on the current webserver in a preview environment?</li>
<li>Or is the
only way to set up a XAMPP environment, import everything, make the
changes, and finally upload it to the real server (including
adaptions to paths and so on)?</li>
</ul>
|
[
{
"answer_id": 194461,
"author": "emilushi",
"author_id": 63983,
"author_profile": "https://wordpress.stackexchange.com/users/63983",
"pm_score": 2,
"selected": false,
"text": "<p>In this case i will do:</p>\n\n<ul>\n<li>create a new folder inside website root folder (ex: mynewsite)</li>\n<li>create a new db and import the old website db to it</li>\n<li>copy old website files and folders to the new directory (mynewsite)</li>\n<li>change db name, user etc in wp-config on mynewsite folder</li>\n<li><p>define site url by adding to wp-config.php</p>\n\n<pre><code>define('WP_HOME','http://youdomain.com/mynewsite');\ndefine('WP_SITEURL','http://example.com/mynewsite');\n</code></pre></li>\n</ul>\n\n<p>after doing this visit <strong><a href=\"http://youdomain.com/mynewsite\" rel=\"nofollow\">http://youdomain.com/mynewsite</a></strong> and start making changes on it, after finishing with the changes you have to change your domain destination to the new directory <strong>mynewsite</strong> that you created and thats all.</p>\n"
},
{
"answer_id": 194501,
"author": "sakibmoon",
"author_id": 23214,
"author_profile": "https://wordpress.stackexchange.com/users/23214",
"pm_score": 1,
"selected": false,
"text": "<ul>\n<li>You setup a Wordpress site in a subdirectory/subdomain or any url of your choice. So, the path structure is up to you. Add all the files and database info in this site. Activate the same plugins and themes.</li>\n<li>Disable search engine indexing for this site.</li>\n<li>Set up so that published posts and everything else on the live site are added automatically in this site periodically.</li>\n</ul>\n\n<p>All the post link won't work for this site as new posts are added. If you want, you can also fix this, but that's not the real goal and extra work without any benefit.</p>\n\n<p>If someone knows the url, they can still access the test site. You might choose some obscure url so that end users don't find it easily and that might be enough. But if this bothers you, password protect it.</p>\n\n<p>Now whenever you need to activate a plugin/do any kind of test use this site. You can be certain about plugin compatibility or any other issue as it is a mirror of the live site. Once you are satisfied, make those changes to the live site.</p>\n\n<p>I like this issue mostly because of the plugin conflicts that arise. More often which works on the development environment breaks the main site for minor issues. This method of testing eliminate that problem.</p>\n\n<p>But it's a lot more work initially and it's up to you whether it's suitable for you. I've found that if you are working on a site for a long time, it saves up lots of hassle and time in the long run.</p>\n"
}
] |
2015/07/14
|
[
"https://wordpress.stackexchange.com/questions/194446",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13921/"
] |
I have a running Wordpress site (3.9.6). Now a new theme should be used and for this theme also some customizations have to be made (content, some WP files like page.php and so on). Additionally, I have to update to Wordpress 4. All changes shouldn't be noticed by visitors or at least as small as possible. Before the site goes live also an editor should get access to edit and add content.
I think this should happen very often and I want to know how do you do that.
* Should a completely new WP site be set up? Should this be done locally or in a subdirectory of the server?
* Is it possible to work
live on the current webserver in a preview environment?
* Or is the
only way to set up a XAMPP environment, import everything, make the
changes, and finally upload it to the real server (including
adaptions to paths and so on)?
|
In this case i will do:
* create a new folder inside website root folder (ex: mynewsite)
* create a new db and import the old website db to it
* copy old website files and folders to the new directory (mynewsite)
* change db name, user etc in wp-config on mynewsite folder
* define site url by adding to wp-config.php
```
define('WP_HOME','http://youdomain.com/mynewsite');
define('WP_SITEURL','http://example.com/mynewsite');
```
after doing this visit **<http://youdomain.com/mynewsite>** and start making changes on it, after finishing with the changes you have to change your domain destination to the new directory **mynewsite** that you created and thats all.
|
194,494 |
<p>I have entered a form element into the page contents editor in wordpress.</p>
<p>form action="/home4/stevekeo/public_html/wp-includes/testforms.php" method="post"> ...</p>
<p>I want to use the selected value, and have created a php script in the /home4/stevekeo/public_html/wp-includes folder to access the user choice.</p>
<pre><code><?php
$team = $_POST['teamname'];
echo "Team selected was ". $team. ".<br />";
?>
</code></pre>
<p>As I understand it, the PHP script named in the 'action' part of the form element is executed when the submit button is clicked. This doesn't appear to happen. Any help would be great, as I'm a relative WP/PHP novice.
sorry - first attempt was mangled</p>
|
[
{
"answer_id": 194461,
"author": "emilushi",
"author_id": 63983,
"author_profile": "https://wordpress.stackexchange.com/users/63983",
"pm_score": 2,
"selected": false,
"text": "<p>In this case i will do:</p>\n\n<ul>\n<li>create a new folder inside website root folder (ex: mynewsite)</li>\n<li>create a new db and import the old website db to it</li>\n<li>copy old website files and folders to the new directory (mynewsite)</li>\n<li>change db name, user etc in wp-config on mynewsite folder</li>\n<li><p>define site url by adding to wp-config.php</p>\n\n<pre><code>define('WP_HOME','http://youdomain.com/mynewsite');\ndefine('WP_SITEURL','http://example.com/mynewsite');\n</code></pre></li>\n</ul>\n\n<p>after doing this visit <strong><a href=\"http://youdomain.com/mynewsite\" rel=\"nofollow\">http://youdomain.com/mynewsite</a></strong> and start making changes on it, after finishing with the changes you have to change your domain destination to the new directory <strong>mynewsite</strong> that you created and thats all.</p>\n"
},
{
"answer_id": 194501,
"author": "sakibmoon",
"author_id": 23214,
"author_profile": "https://wordpress.stackexchange.com/users/23214",
"pm_score": 1,
"selected": false,
"text": "<ul>\n<li>You setup a Wordpress site in a subdirectory/subdomain or any url of your choice. So, the path structure is up to you. Add all the files and database info in this site. Activate the same plugins and themes.</li>\n<li>Disable search engine indexing for this site.</li>\n<li>Set up so that published posts and everything else on the live site are added automatically in this site periodically.</li>\n</ul>\n\n<p>All the post link won't work for this site as new posts are added. If you want, you can also fix this, but that's not the real goal and extra work without any benefit.</p>\n\n<p>If someone knows the url, they can still access the test site. You might choose some obscure url so that end users don't find it easily and that might be enough. But if this bothers you, password protect it.</p>\n\n<p>Now whenever you need to activate a plugin/do any kind of test use this site. You can be certain about plugin compatibility or any other issue as it is a mirror of the live site. Once you are satisfied, make those changes to the live site.</p>\n\n<p>I like this issue mostly because of the plugin conflicts that arise. More often which works on the development environment breaks the main site for minor issues. This method of testing eliminate that problem.</p>\n\n<p>But it's a lot more work initially and it's up to you whether it's suitable for you. I've found that if you are working on a site for a long time, it saves up lots of hassle and time in the long run.</p>\n"
}
] |
2015/07/14
|
[
"https://wordpress.stackexchange.com/questions/194494",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76194/"
] |
I have entered a form element into the page contents editor in wordpress.
form action="/home4/stevekeo/public\_html/wp-includes/testforms.php" method="post"> ...
I want to use the selected value, and have created a php script in the /home4/stevekeo/public\_html/wp-includes folder to access the user choice.
```
<?php
$team = $_POST['teamname'];
echo "Team selected was ". $team. ".<br />";
?>
```
As I understand it, the PHP script named in the 'action' part of the form element is executed when the submit button is clicked. This doesn't appear to happen. Any help would be great, as I'm a relative WP/PHP novice.
sorry - first attempt was mangled
|
In this case i will do:
* create a new folder inside website root folder (ex: mynewsite)
* create a new db and import the old website db to it
* copy old website files and folders to the new directory (mynewsite)
* change db name, user etc in wp-config on mynewsite folder
* define site url by adding to wp-config.php
```
define('WP_HOME','http://youdomain.com/mynewsite');
define('WP_SITEURL','http://example.com/mynewsite');
```
after doing this visit **<http://youdomain.com/mynewsite>** and start making changes on it, after finishing with the changes you have to change your domain destination to the new directory **mynewsite** that you created and thats all.
|
194,516 |
<p>Having an issue where I have a client who wants his Google Analytics code on just one page. I'm using the following is_page code but in the <strong><code>footer.php</code></strong> of my child theme, but it's not appearing on the page. Is this code correct?</p>
<pre><code><?php if ( is_page( 'contact' )) {
echo '<script type="text/javascript">/* <![CDATA[ */
var google_conversion_id = 000000000;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "000000000";
var google_remarketing_only = false;
/* ]]> */</script>
<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js"></script>
<noscript><div style="display:inline;"><img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/conversion/000000000/?label=000000000&amp;guid=ON&amp;script=0"/></div></noscript>';
} ?>
</code></pre>
|
[
{
"answer_id": 194502,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 2,
"selected": false,
"text": "<p>In menu editor add <strong>Custom Link</strong> for each language with <strong>URL</strong> pointing to the site of your language and <strong>Link Text</strong> - <code><img src=\"url of your flag picture\" alt=\"your language\"></code></p>\n"
},
{
"answer_id": 298303,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 2,
"selected": false,
"text": "<p>You can add your flag (plain) html into menu at last li tag.</p>\n\n<pre><code><?php\nfunction add_last_nav_item($items, $args) {\n if ($args->menu->slug == 'topbar-menu') { // change your menu slug name\n\n // Add your html\n $item = '<li class=\"searchbox\"> \n <input type=\"search\" placeholder=\"Search......\" name=\"search\" class=\"searchbox-input\" onkeyup=\"buttonUp();\" required>\n <input type=\"submit\" class=\"searchbox-submit\" value=\"\">\n <span class=\"searchbox-icon\"><i class=\"fa fa-search\"></i></span>\n </li>';\n $items = $item.$items;\n }\n return $items;\n}\nadd_filter( 'wp_nav_menu_items', 'add_last_nav_item', 10, 2 );\n?>\n</code></pre>\n"
}
] |
2015/07/14
|
[
"https://wordpress.stackexchange.com/questions/194516",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64741/"
] |
Having an issue where I have a client who wants his Google Analytics code on just one page. I'm using the following is\_page code but in the **`footer.php`** of my child theme, but it's not appearing on the page. Is this code correct?
```
<?php if ( is_page( 'contact' )) {
echo '<script type="text/javascript">/* <![CDATA[ */
var google_conversion_id = 000000000;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "000000000";
var google_remarketing_only = false;
/* ]]> */</script>
<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js"></script>
<noscript><div style="display:inline;"><img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/conversion/000000000/?label=000000000&guid=ON&script=0"/></div></noscript>';
} ?>
```
|
In menu editor add **Custom Link** for each language with **URL** pointing to the site of your language and **Link Text** - `<img src="url of your flag picture" alt="your language">`
|
194,571 |
<p>One of <a href="http://www.michalzucker.com" rel="nofollow">my client's sites</a> are in Hebrew which is a right-to-left language. </p>
<p>I'm using the <a href="https://wordpress.org/themes/mh-newsdesk-lite/" rel="nofollow">MH Newsdesk Lite theme</a> found on <a href="https://codex.wordpress.org/CSS#WordPress_Generated_Classes" rel="nofollow">wordpress.org</a> . The theme is using a <strong><a href="https://codex.wordpress.org/CSS#WordPress_Generated_Classes" rel="nofollow">core</a></strong> wordpress generated class <code>.screen-reader-text{}</code> to display the search form with <code>get_search_form()</code>. </p>
<p>The issue is there's text, specifically "חפס", overflowing off the page on the left. I believe this is due to the fact that it's being displayed in rtl language. I want to make it so the homepage (And possibly some of the other pages and posts, too), <em><strong>never</strong></em> scroll to the x-axis. What is the best practice for theme developers and users of these theme to use <code>.screen-reader-text{}</code> while maintaining accessibility and not messing up the display (like the page scrolling horizontally in my case)?</p>
<p>Here are some links I've found that are relevant:
<a href="https://make.wordpress.org/accessibility/tag/screen-reader/" rel="nofollow">https://make.wordpress.org/accessibility/tag/screen-reader/</a>
<a href="https://make.wordpress.org/themes/2015/01/26/supporting-screen-reader-text/" rel="nofollow">https://make.wordpress.org/themes/2015/01/26/supporting-screen-reader-text/</a></p>
|
[
{
"answer_id": 194578,
"author": "Vee",
"author_id": 44979,
"author_profile": "https://wordpress.stackexchange.com/users/44979",
"pm_score": 1,
"selected": true,
"text": "<p>It is due to css:</p>\n\n<p>Check this(Line # 314 style.css):</p>\n\n<pre><code>.search-form .screen-reader-text {\n left: -9999px;\n overflow: hidden;\n position: absolute;\n}\n</code></pre>\n\n<p>Remove the left margin then it works fine. It is on sidebar search form. Sorry for English.</p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 194584,
"author": "Dub Scrib",
"author_id": 75797,
"author_profile": "https://wordpress.stackexchange.com/users/75797",
"pm_score": 1,
"selected": false,
"text": "<p>Context: accessibility guidance says forms should have labels. The theme designer obviously decided they didn't want the label there but used that CSS trick to move it without (completely) disobeying the guidance. </p>\n\n<p>However, that code only hides the search form label off the left of a page in English (or other Left to Right language). Since Hebrew is Right to Left the text is appearing and making the page really wide. </p>\n\n<p>The quick fix is to hide it to the right instead of the left. @Vee's answer brings the text label back next to the form, if you want it there. </p>\n\n<p>You may be being downvoted as someone thinks you're asking the wrong question or <a href=\"https://stackoverflow.com/questions/12284514/inverted-css-properties-to-change-to-rtl\">you haven't researched it properly</a>, or something else.</p>\n"
},
{
"answer_id": 194587,
"author": "Bryan Willis",
"author_id": 38123,
"author_profile": "https://wordpress.stackexchange.com/users/38123",
"pm_score": 0,
"selected": false,
"text": "<p>@Vee's method will work, but if you want to keep it hidden from display use this method :</p>\n\n<pre><code>.search-form .screen-reader-text {\n overflow: hidden;\n clip: rect(1px, 1px, 1px, 1px);\n position: absolute !important;\n height: 1px;\n width: 1px; \n}\n</code></pre>\n\n<p>It looks like you have a jetpack custom css plugin installed so just add this there, then you don't have to mess with the parent theme.</p>\n"
}
] |
2015/07/15
|
[
"https://wordpress.stackexchange.com/questions/194571",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75345/"
] |
One of [my client's sites](http://www.michalzucker.com) are in Hebrew which is a right-to-left language.
I'm using the [MH Newsdesk Lite theme](https://wordpress.org/themes/mh-newsdesk-lite/) found on [wordpress.org](https://codex.wordpress.org/CSS#WordPress_Generated_Classes) . The theme is using a **[core](https://codex.wordpress.org/CSS#WordPress_Generated_Classes)** wordpress generated class `.screen-reader-text{}` to display the search form with `get_search_form()`.
The issue is there's text, specifically "חפס", overflowing off the page on the left. I believe this is due to the fact that it's being displayed in rtl language. I want to make it so the homepage (And possibly some of the other pages and posts, too), ***never*** scroll to the x-axis. What is the best practice for theme developers and users of these theme to use `.screen-reader-text{}` while maintaining accessibility and not messing up the display (like the page scrolling horizontally in my case)?
Here are some links I've found that are relevant:
<https://make.wordpress.org/accessibility/tag/screen-reader/>
<https://make.wordpress.org/themes/2015/01/26/supporting-screen-reader-text/>
|
It is due to css:
Check this(Line # 314 style.css):
```
.search-form .screen-reader-text {
left: -9999px;
overflow: hidden;
position: absolute;
}
```
Remove the left margin then it works fine. It is on sidebar search form. Sorry for English.
Thanks
|
194,581 |
<p>I've got a <code>staff_member</code> custom post type, with <code>'has_archive' => true</code>. I've got an <code>archive-staff_member.php</code> template, with <code>/* Template Name: Staff */
</code></p>
<p>In backoffice, to add it to the nav menu, I created a page and assigned the template Staff, then added it to the main menu.</p>
<p>Till here, all fine. The problem is that when I navigate to the staff page, even if archive-staff_member.php is correctly loaded, wp_query is wrong. In other words, <code>is_post_type_archive()</code> and <code>is_post_type_archive('staff_member')</code> return false.</p>
<p>So what's the problem here?</p>
<p>For now I'm using just a custom query, but it would be better automated archive, as stated by official docs.</p>
<p>And by the way: it would be better if there was a way to add the archive from the menu page, instead of creating a 'dumb' staff page.</p>
|
[
{
"answer_id": 194589,
"author": "Trang",
"author_id": 70868,
"author_profile": "https://wordpress.stackexchange.com/users/70868",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, the function is_post_type_archive only works in archive.php\nTo have an item on nav menu links to your staff_member, you will add a custom link menu item in stead of a page whose template is your file tempate.\nThe URL of that item will be got when you vardump this:</p>\n\n<pre><code>get_post_type_archive_link('staff_member')\n</code></pre>\n\n<p>And to custom the performance of the staff_member, use is_post_type_archive('staff_member') in the file archives.php of the theme.</p>\n"
},
{
"answer_id": 194590,
"author": "Marek",
"author_id": 54031,
"author_profile": "https://wordpress.stackexchange.com/users/54031",
"pm_score": 2,
"selected": false,
"text": "<p>Custom post type archive page does not need \"dumb\" Page. In fact, there could be the culprit. You should try this:</p>\n\n<ol>\n<li>Remove <code>/* Template Name: Staff */</code> from archive-staff_member.php (not needed)</li>\n<li>Remove \"dumb\" stuff Page (if created). There could be some permalink conflict.</li>\n<li>Go to Admin > Settings > Permalinks and re-save it (it will regenerate rewrite rules)</li>\n<li>Now just type URL ... yoursite.com/staff_member/ (depends on <code>rewrite</code> setting in your <code>register_post_type(...)</code> )</li>\n</ol>\n\n<p>You should see only \"staff member\" posts. If yes, than wp_query is correct and <code>is_post_type_archive()</code> will returns true. If it uses correct archive template too, you are done :) If not (maybe 404 error?), then there is some misconfiguration.</p>\n\n<p>And when you have <code>yoursite.com/staff_member/</code> URL, you can add it to nav menu as \"Custom link\". No \"dumb\" Page creation needed.</p>\n"
},
{
"answer_id": 194598,
"author": "shashikant",
"author_id": 76189,
"author_profile": "https://wordpress.stackexchange.com/users/76189",
"pm_score": 0,
"selected": false,
"text": "<p>Just create an <code>archive-{post_type}.php</code> when you create a custom post type and include this function: <code>flush_rewrite_rules();</code> </p>\n\n<p>Make a page of your custom post type. It's called an archive page.</p>\n"
},
{
"answer_id": 194668,
"author": "Luca Reghellin",
"author_id": 10381,
"author_profile": "https://wordpress.stackexchange.com/users/10381",
"pm_score": 1,
"selected": true,
"text": "<p>Ok, an answer to all. First, thank you for you help. </p>\n\n<p><strike>Anyway, none of your solutions really address my issue. I don't like custom links on nav menus, at all</strike>. And that's because they're not dynamic, you cannot build them dynamically. So <strike>when you move the site and change url (for example, from staging to production) you'll have to remember to manually change the links</strike>. Also, the client, who often is not a programmer, nor too used to computer/web/urls things, won't be able to properly manage it by himself.</p>\n\n<p><strong>EDIT: I've found a solution to the above issue, so now Marek's answer can be considered reliable, at least to me: we can filter the nav_menu-generated urls so that they'll always use real site url:</strong></p>\n\n<pre><code>function normalize_url($atts){\n if( !parse_url($atts['href'], PHP_URL_SCHEME) && $atts['href'] != '#'){\n $atts['href'] = site_url() . $atts['href'];\n }\n return $atts;\n}\n\nadd_filter('nav_menu_link_attributes', 'normalize_url');\n\n\n//Marek's way will cause wp_nav_menu not to correctly \n//output parent/child classes, so here's an example of \n//how to solve this issue too:\nfunction fix_nav_classes($classes, $item){\n\n //say I've got some custom links: the 'Projects' parent and a child that \n //points to '/selected_project/' and I want always these classes for both \n //parents and child items\n if(is_post_type_archive('project') || get_post_type() == 'project'){\n if($item->post_title == 'Projects') $classes[] = 'current-menu-parent';\n if($item->url == '/selected_project/') $classes[] = 'current-menu-item';\n }\n\n return $classes;\n}\n\nadd_filter( 'nav_menu_css_class', 'fix_nav_classes', 10, 2 ); \n</code></pre>\n\n<p><strong>OLD ANSWER > good as alternative:</strong></p>\n\n<p>The problem here, is that wordpress consider the 'page' nature first: if you assign a custom post type template (according to rules) to a page, that will not work. I think it's probably a permalink thing -> page has different permalink than the archive. I think I could fix just modifying the page's permalink OR the rewrite rule on register_post_type so that the 2 are the same, but this is not a good practice too.</p>\n\n<p>So for now, just dumb page and a 'classic' custom query. For those who need, just this:</p>\n\n<pre><code>global $wp_query;\n\n$query_array = array(\n 'posts_per_page' => 15,\n 'post_type' => 'staff_member',\n 'post_status' => 'publish',\n 'orderby' => 'menu_order',\n 'order' => 'ASC'\n);\n\n$member = $wp_query->query($query_array);\n</code></pre>\n\n<p>I generally use this kind of code.. If one really needs all the wp sugar, he can also substitute the main query:</p>\n\n<pre><code>global $wp_query;\n$original = $wp_query; // save for restore\n$wp_query = new WP_Query();\n\n$wp_query->query(array(\n 'posts_per_page' => 15,\n 'post_type' => 'staff_member',\n 'post_status' => 'publish',\n 'orderby' => 'menu_order',\n 'order' => 'ASC'\n );\n\n// here goes processing code and sugars\n// if(have_posts()): while(have_posts()): the_post(); etc etc.. the_content() etc..\n\n// restore the original\n$wp_query = $original;\n</code></pre>\n\n<p>Have a nice day!</p>\n"
}
] |
2015/07/15
|
[
"https://wordpress.stackexchange.com/questions/194581",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10381/"
] |
I've got a `staff_member` custom post type, with `'has_archive' => true`. I've got an `archive-staff_member.php` template, with `/* Template Name: Staff */`
In backoffice, to add it to the nav menu, I created a page and assigned the template Staff, then added it to the main menu.
Till here, all fine. The problem is that when I navigate to the staff page, even if archive-staff\_member.php is correctly loaded, wp\_query is wrong. In other words, `is_post_type_archive()` and `is_post_type_archive('staff_member')` return false.
So what's the problem here?
For now I'm using just a custom query, but it would be better automated archive, as stated by official docs.
And by the way: it would be better if there was a way to add the archive from the menu page, instead of creating a 'dumb' staff page.
|
Ok, an answer to all. First, thank you for you help.
Anyway, none of your solutions really address my issue. I don't like custom links on nav menus, at all. And that's because they're not dynamic, you cannot build them dynamically. So when you move the site and change url (for example, from staging to production) you'll have to remember to manually change the links. Also, the client, who often is not a programmer, nor too used to computer/web/urls things, won't be able to properly manage it by himself.
**EDIT: I've found a solution to the above issue, so now Marek's answer can be considered reliable, at least to me: we can filter the nav\_menu-generated urls so that they'll always use real site url:**
```
function normalize_url($atts){
if( !parse_url($atts['href'], PHP_URL_SCHEME) && $atts['href'] != '#'){
$atts['href'] = site_url() . $atts['href'];
}
return $atts;
}
add_filter('nav_menu_link_attributes', 'normalize_url');
//Marek's way will cause wp_nav_menu not to correctly
//output parent/child classes, so here's an example of
//how to solve this issue too:
function fix_nav_classes($classes, $item){
//say I've got some custom links: the 'Projects' parent and a child that
//points to '/selected_project/' and I want always these classes for both
//parents and child items
if(is_post_type_archive('project') || get_post_type() == 'project'){
if($item->post_title == 'Projects') $classes[] = 'current-menu-parent';
if($item->url == '/selected_project/') $classes[] = 'current-menu-item';
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'fix_nav_classes', 10, 2 );
```
**OLD ANSWER > good as alternative:**
The problem here, is that wordpress consider the 'page' nature first: if you assign a custom post type template (according to rules) to a page, that will not work. I think it's probably a permalink thing -> page has different permalink than the archive. I think I could fix just modifying the page's permalink OR the rewrite rule on register\_post\_type so that the 2 are the same, but this is not a good practice too.
So for now, just dumb page and a 'classic' custom query. For those who need, just this:
```
global $wp_query;
$query_array = array(
'posts_per_page' => 15,
'post_type' => 'staff_member',
'post_status' => 'publish',
'orderby' => 'menu_order',
'order' => 'ASC'
);
$member = $wp_query->query($query_array);
```
I generally use this kind of code.. If one really needs all the wp sugar, he can also substitute the main query:
```
global $wp_query;
$original = $wp_query; // save for restore
$wp_query = new WP_Query();
$wp_query->query(array(
'posts_per_page' => 15,
'post_type' => 'staff_member',
'post_status' => 'publish',
'orderby' => 'menu_order',
'order' => 'ASC'
);
// here goes processing code and sugars
// if(have_posts()): while(have_posts()): the_post(); etc etc.. the_content() etc..
// restore the original
$wp_query = $original;
```
Have a nice day!
|
194,612 |
<p>How do I change the position of the Products menu? I created it by hard coding, using the code below.</p>
<p><img src="https://i.stack.imgur.com/84PVu.png" alt="enter image description here"></p>
<pre><code>add_filter( 'the_content', 'filter_ptags_on_images' );
add_filter( 'wp_nav_menu_items', 'add_my_terms', 10, 2 );
function add_my_terms( $items ) {
global $post;
$items .= '<li class="dropdown "><a class="dropdown-toggle " data-toggle="dropdown" href="#">Products</a><ul class="dropdown-menu coldrpprd ">';
$terms = get_terms( 'product_cat', $args );
$nmr=0;
$args = array(
'hierarchical' => 1,
'show_option_none' => '',
'hide_empty' => 0,
'parent' => $term->term_id,
'taxonomy' => 'product_cat'
);
$subcats = get_terms( 'product_cat', $args );
foreach ( $terms as $term ) {
$category_name = $term->name;
$category_thumbnail = get_woocommerce_term_meta($term->term_id, 'thumbnail_id', true);
$image = wp_get_attachment_url($category_thumbnail);
$nmr++ ;
if ( $nmr <= 3 ) {
$items .= '<li class="menuli">'.'<img class="category-image " src="'.$image.'">'.'<a href="' . get_term_link($term) . '">' . $term->name . '</a></li>';
$items .= '<ul>';
foreach ( $subcats as $sc ) {
$link = get_term_link( $sc->slug, $sc->taxonomy );
$items .= '<li class="wooc_sclist"><a href="'. $link .'">'.$sc->name.'</a></li>';
}
$items .= '</ul>';
}
}
$items .= '</ul></li>';
return $items;
}
</code></pre>
|
[
{
"answer_id": 194589,
"author": "Trang",
"author_id": 70868,
"author_profile": "https://wordpress.stackexchange.com/users/70868",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, the function is_post_type_archive only works in archive.php\nTo have an item on nav menu links to your staff_member, you will add a custom link menu item in stead of a page whose template is your file tempate.\nThe URL of that item will be got when you vardump this:</p>\n\n<pre><code>get_post_type_archive_link('staff_member')\n</code></pre>\n\n<p>And to custom the performance of the staff_member, use is_post_type_archive('staff_member') in the file archives.php of the theme.</p>\n"
},
{
"answer_id": 194590,
"author": "Marek",
"author_id": 54031,
"author_profile": "https://wordpress.stackexchange.com/users/54031",
"pm_score": 2,
"selected": false,
"text": "<p>Custom post type archive page does not need \"dumb\" Page. In fact, there could be the culprit. You should try this:</p>\n\n<ol>\n<li>Remove <code>/* Template Name: Staff */</code> from archive-staff_member.php (not needed)</li>\n<li>Remove \"dumb\" stuff Page (if created). There could be some permalink conflict.</li>\n<li>Go to Admin > Settings > Permalinks and re-save it (it will regenerate rewrite rules)</li>\n<li>Now just type URL ... yoursite.com/staff_member/ (depends on <code>rewrite</code> setting in your <code>register_post_type(...)</code> )</li>\n</ol>\n\n<p>You should see only \"staff member\" posts. If yes, than wp_query is correct and <code>is_post_type_archive()</code> will returns true. If it uses correct archive template too, you are done :) If not (maybe 404 error?), then there is some misconfiguration.</p>\n\n<p>And when you have <code>yoursite.com/staff_member/</code> URL, you can add it to nav menu as \"Custom link\". No \"dumb\" Page creation needed.</p>\n"
},
{
"answer_id": 194598,
"author": "shashikant",
"author_id": 76189,
"author_profile": "https://wordpress.stackexchange.com/users/76189",
"pm_score": 0,
"selected": false,
"text": "<p>Just create an <code>archive-{post_type}.php</code> when you create a custom post type and include this function: <code>flush_rewrite_rules();</code> </p>\n\n<p>Make a page of your custom post type. It's called an archive page.</p>\n"
},
{
"answer_id": 194668,
"author": "Luca Reghellin",
"author_id": 10381,
"author_profile": "https://wordpress.stackexchange.com/users/10381",
"pm_score": 1,
"selected": true,
"text": "<p>Ok, an answer to all. First, thank you for you help. </p>\n\n<p><strike>Anyway, none of your solutions really address my issue. I don't like custom links on nav menus, at all</strike>. And that's because they're not dynamic, you cannot build them dynamically. So <strike>when you move the site and change url (for example, from staging to production) you'll have to remember to manually change the links</strike>. Also, the client, who often is not a programmer, nor too used to computer/web/urls things, won't be able to properly manage it by himself.</p>\n\n<p><strong>EDIT: I've found a solution to the above issue, so now Marek's answer can be considered reliable, at least to me: we can filter the nav_menu-generated urls so that they'll always use real site url:</strong></p>\n\n<pre><code>function normalize_url($atts){\n if( !parse_url($atts['href'], PHP_URL_SCHEME) && $atts['href'] != '#'){\n $atts['href'] = site_url() . $atts['href'];\n }\n return $atts;\n}\n\nadd_filter('nav_menu_link_attributes', 'normalize_url');\n\n\n//Marek's way will cause wp_nav_menu not to correctly \n//output parent/child classes, so here's an example of \n//how to solve this issue too:\nfunction fix_nav_classes($classes, $item){\n\n //say I've got some custom links: the 'Projects' parent and a child that \n //points to '/selected_project/' and I want always these classes for both \n //parents and child items\n if(is_post_type_archive('project') || get_post_type() == 'project'){\n if($item->post_title == 'Projects') $classes[] = 'current-menu-parent';\n if($item->url == '/selected_project/') $classes[] = 'current-menu-item';\n }\n\n return $classes;\n}\n\nadd_filter( 'nav_menu_css_class', 'fix_nav_classes', 10, 2 ); \n</code></pre>\n\n<p><strong>OLD ANSWER > good as alternative:</strong></p>\n\n<p>The problem here, is that wordpress consider the 'page' nature first: if you assign a custom post type template (according to rules) to a page, that will not work. I think it's probably a permalink thing -> page has different permalink than the archive. I think I could fix just modifying the page's permalink OR the rewrite rule on register_post_type so that the 2 are the same, but this is not a good practice too.</p>\n\n<p>So for now, just dumb page and a 'classic' custom query. For those who need, just this:</p>\n\n<pre><code>global $wp_query;\n\n$query_array = array(\n 'posts_per_page' => 15,\n 'post_type' => 'staff_member',\n 'post_status' => 'publish',\n 'orderby' => 'menu_order',\n 'order' => 'ASC'\n);\n\n$member = $wp_query->query($query_array);\n</code></pre>\n\n<p>I generally use this kind of code.. If one really needs all the wp sugar, he can also substitute the main query:</p>\n\n<pre><code>global $wp_query;\n$original = $wp_query; // save for restore\n$wp_query = new WP_Query();\n\n$wp_query->query(array(\n 'posts_per_page' => 15,\n 'post_type' => 'staff_member',\n 'post_status' => 'publish',\n 'orderby' => 'menu_order',\n 'order' => 'ASC'\n );\n\n// here goes processing code and sugars\n// if(have_posts()): while(have_posts()): the_post(); etc etc.. the_content() etc..\n\n// restore the original\n$wp_query = $original;\n</code></pre>\n\n<p>Have a nice day!</p>\n"
}
] |
2015/07/15
|
[
"https://wordpress.stackexchange.com/questions/194612",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76247/"
] |
How do I change the position of the Products menu? I created it by hard coding, using the code below.

```
add_filter( 'the_content', 'filter_ptags_on_images' );
add_filter( 'wp_nav_menu_items', 'add_my_terms', 10, 2 );
function add_my_terms( $items ) {
global $post;
$items .= '<li class="dropdown "><a class="dropdown-toggle " data-toggle="dropdown" href="#">Products</a><ul class="dropdown-menu coldrpprd ">';
$terms = get_terms( 'product_cat', $args );
$nmr=0;
$args = array(
'hierarchical' => 1,
'show_option_none' => '',
'hide_empty' => 0,
'parent' => $term->term_id,
'taxonomy' => 'product_cat'
);
$subcats = get_terms( 'product_cat', $args );
foreach ( $terms as $term ) {
$category_name = $term->name;
$category_thumbnail = get_woocommerce_term_meta($term->term_id, 'thumbnail_id', true);
$image = wp_get_attachment_url($category_thumbnail);
$nmr++ ;
if ( $nmr <= 3 ) {
$items .= '<li class="menuli">'.'<img class="category-image " src="'.$image.'">'.'<a href="' . get_term_link($term) . '">' . $term->name . '</a></li>';
$items .= '<ul>';
foreach ( $subcats as $sc ) {
$link = get_term_link( $sc->slug, $sc->taxonomy );
$items .= '<li class="wooc_sclist"><a href="'. $link .'">'.$sc->name.'</a></li>';
}
$items .= '</ul>';
}
}
$items .= '</ul></li>';
return $items;
}
```
|
Ok, an answer to all. First, thank you for you help.
Anyway, none of your solutions really address my issue. I don't like custom links on nav menus, at all. And that's because they're not dynamic, you cannot build them dynamically. So when you move the site and change url (for example, from staging to production) you'll have to remember to manually change the links. Also, the client, who often is not a programmer, nor too used to computer/web/urls things, won't be able to properly manage it by himself.
**EDIT: I've found a solution to the above issue, so now Marek's answer can be considered reliable, at least to me: we can filter the nav\_menu-generated urls so that they'll always use real site url:**
```
function normalize_url($atts){
if( !parse_url($atts['href'], PHP_URL_SCHEME) && $atts['href'] != '#'){
$atts['href'] = site_url() . $atts['href'];
}
return $atts;
}
add_filter('nav_menu_link_attributes', 'normalize_url');
//Marek's way will cause wp_nav_menu not to correctly
//output parent/child classes, so here's an example of
//how to solve this issue too:
function fix_nav_classes($classes, $item){
//say I've got some custom links: the 'Projects' parent and a child that
//points to '/selected_project/' and I want always these classes for both
//parents and child items
if(is_post_type_archive('project') || get_post_type() == 'project'){
if($item->post_title == 'Projects') $classes[] = 'current-menu-parent';
if($item->url == '/selected_project/') $classes[] = 'current-menu-item';
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'fix_nav_classes', 10, 2 );
```
**OLD ANSWER > good as alternative:**
The problem here, is that wordpress consider the 'page' nature first: if you assign a custom post type template (according to rules) to a page, that will not work. I think it's probably a permalink thing -> page has different permalink than the archive. I think I could fix just modifying the page's permalink OR the rewrite rule on register\_post\_type so that the 2 are the same, but this is not a good practice too.
So for now, just dumb page and a 'classic' custom query. For those who need, just this:
```
global $wp_query;
$query_array = array(
'posts_per_page' => 15,
'post_type' => 'staff_member',
'post_status' => 'publish',
'orderby' => 'menu_order',
'order' => 'ASC'
);
$member = $wp_query->query($query_array);
```
I generally use this kind of code.. If one really needs all the wp sugar, he can also substitute the main query:
```
global $wp_query;
$original = $wp_query; // save for restore
$wp_query = new WP_Query();
$wp_query->query(array(
'posts_per_page' => 15,
'post_type' => 'staff_member',
'post_status' => 'publish',
'orderby' => 'menu_order',
'order' => 'ASC'
);
// here goes processing code and sugars
// if(have_posts()): while(have_posts()): the_post(); etc etc.. the_content() etc..
// restore the original
$wp_query = $original;
```
Have a nice day!
|
194,618 |
<p>I am including a pure PHP library (nothing to do with WordPress) into a few of my page templates. This library calls PHP session_start() function and references the $_SESSION["cart"] global variable. Because of the session_start I include the library at the top of my template.</p>
<p>When I am logged in the library functions exactly as it is supposed to, but when I log out, the $_SESSION variables appear not to store data. Any ideas to fix this?</p>
|
[
{
"answer_id": 194621,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 4,
"selected": true,
"text": "<p>WordPress doesn't use PHP sessions, so WordPress itself can not be related with your sessions working or not regarding if you are logged in or not (I think).</p>\n\n<p>Try to call <code>session_start()</code> on <code>init</code> action instead of doing it in a template file and be sure it is called before your custom library is loaded. Also, it can be interesting to end the PHP session on user log in and user log out to start a fresh one:</p>\n\n<pre><code>add_action('init', 'cyb_start_session', 1);\nadd_action('wp_logout', 'cyb_end_session');\nadd_action('wp_login', 'cyb_end_session');\n\nfunction cyb_start_session() {\n if( ! session_id() ) {\n session_start();\n // now you can load your library that use $_SESSION\n }\n}\n\nfunction cyb_end_session() {\n session_destroy();\n}\n</code></pre>\n\n<p>Because you library calls <code>session_start()</code>, con avoid to call it yourself but you still needs to load your library on <code>init</code> and destroy sessions on log in/log out:</p>\n\n<pre><code>add_action('init', 'cyb_start_session', 1);\nadd_action('wp_logout', 'cyb_end_session');\nadd_action('wp_login', 'cyb_end_session');\n\nfunction cyb_start_session() {\n // load your libreary here (assuming it calls session_start())\n}\n\nfunction cyb_end_session() {\n session_destroy();\n}\n</code></pre>\n\n<p>The key is to start PHP sessions as earlier as possible, before output anything. On <code>init</code> with priority 1 is the earliest it can be done in WP enviroment. If you do before, session can be destroyed by <a href=\"https://codex.wordpress.org/Function_Reference/wp_unregister_GLOBALS\" rel=\"noreferrer\">wp_unregister_GLOBALS()</a>.</p>\n\n<p>A basic and silly but working example:</p>\n\n<pre><code>add_action('init', 'cyb_start_session', 1);\nadd_action('wp_logout', 'cyb_end_session');\nadd_action('wp_login', 'cyb_end_session');\n\nfunction cyb_start_session() {\n if( ! session_id() ) {\n session_start();\n // now you can use $_SESSION\n $_SESSION['test'] = \"test\";\n }\n}\n\nfunction cyb_end_session() {\n session_destroy();\n}\n\n\n// This will print array(1) { [\"test\"]=> string(4) \"test\" }\n// above the content of any post\nadd_filter( 'the_content', function( $content ) {\n\n var_dump($_SESSION);\n\n return $content;\n\n} );\n</code></pre>\n"
},
{
"answer_id": 379005,
"author": "Roddy P. Carbonell",
"author_id": 198235,
"author_profile": "https://wordpress.stackexchange.com/users/198235",
"pm_score": 2,
"selected": false,
"text": "<p>I have been thinking about using Wordpress' meta keys as session variables. Something like this:</p>\n<pre><code>add_user_meta(\n int $user_id,\n string $meta_key,\n mixed $meta_value,\n bool $unique = false\n);\n</code></pre>\n<p>Wordpress will keep the meta values, link them to a user, and you can delete those values later on.</p>\n"
}
] |
2015/07/15
|
[
"https://wordpress.stackexchange.com/questions/194618",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71479/"
] |
I am including a pure PHP library (nothing to do with WordPress) into a few of my page templates. This library calls PHP session\_start() function and references the $\_SESSION["cart"] global variable. Because of the session\_start I include the library at the top of my template.
When I am logged in the library functions exactly as it is supposed to, but when I log out, the $\_SESSION variables appear not to store data. Any ideas to fix this?
|
WordPress doesn't use PHP sessions, so WordPress itself can not be related with your sessions working or not regarding if you are logged in or not (I think).
Try to call `session_start()` on `init` action instead of doing it in a template file and be sure it is called before your custom library is loaded. Also, it can be interesting to end the PHP session on user log in and user log out to start a fresh one:
```
add_action('init', 'cyb_start_session', 1);
add_action('wp_logout', 'cyb_end_session');
add_action('wp_login', 'cyb_end_session');
function cyb_start_session() {
if( ! session_id() ) {
session_start();
// now you can load your library that use $_SESSION
}
}
function cyb_end_session() {
session_destroy();
}
```
Because you library calls `session_start()`, con avoid to call it yourself but you still needs to load your library on `init` and destroy sessions on log in/log out:
```
add_action('init', 'cyb_start_session', 1);
add_action('wp_logout', 'cyb_end_session');
add_action('wp_login', 'cyb_end_session');
function cyb_start_session() {
// load your libreary here (assuming it calls session_start())
}
function cyb_end_session() {
session_destroy();
}
```
The key is to start PHP sessions as earlier as possible, before output anything. On `init` with priority 1 is the earliest it can be done in WP enviroment. If you do before, session can be destroyed by [wp\_unregister\_GLOBALS()](https://codex.wordpress.org/Function_Reference/wp_unregister_GLOBALS).
A basic and silly but working example:
```
add_action('init', 'cyb_start_session', 1);
add_action('wp_logout', 'cyb_end_session');
add_action('wp_login', 'cyb_end_session');
function cyb_start_session() {
if( ! session_id() ) {
session_start();
// now you can use $_SESSION
$_SESSION['test'] = "test";
}
}
function cyb_end_session() {
session_destroy();
}
// This will print array(1) { ["test"]=> string(4) "test" }
// above the content of any post
add_filter( 'the_content', function( $content ) {
var_dump($_SESSION);
return $content;
} );
```
|
194,634 |
<p>I just not only want to override a <code>pluggable function</code> (<code>wp_new_user_notification</code>) but I want to make sure that if any other plugin is overriding the same function, so my function , override that too or I want my overridden function to work instead of other plugin that is overriding the same function (<code>wp_new_user_notification</code>). May be a silly question but can I do it ??</p>
|
[
{
"answer_id": 194638,
"author": "TheGentleman",
"author_id": 68563,
"author_profile": "https://wordpress.stackexchange.com/users/68563",
"pm_score": 2,
"selected": false,
"text": "<p>The short answer to your question is yes; however, the methods to do this are a little bit hacky and generally I would recommend against all of them unless absolutely necessary.</p>\n\n<p>Since <code>pluggable functions</code> actually replace the stock function by way of <code>function_exists()</code> whichever plugin that \"plugs\" the function first will win. What you want to do is ensure your plugin loads first globally.</p>\n\n<p>Plugins are loaded according to their order in an array stored in the <code>wp_options</code> table. This array is sorted alphabetically. Knowing that, you have 2 options.</p>\n\n<ol>\n<li><strong>Make it very likely that your plugin is alphabetically first.</strong> I <strong><em>believe</em></strong> that <code>@</code> is considered alphabetically first in php, so if you start your plugin name with something like <code>@@MyPlugin</code> then it should get loaded first.</li>\n<li><p><strong>Change the order of the array stored in the database using the <code>activated_plugin</code> hook.</strong> I did a quick google search and found that someone had already written a function <a href=\"http://snippets.khromov.se/modify-wordpress-plugin-load-order/\" rel=\"nofollow\">here</a>. I've re-posted it below in case the link goes dead.</p>\n\n<pre><code>add_action( 'activated_plugin', 'my_plugin_load_first' );\nfunction my_plugin_load_first(){\n $path = str_replace( WP_PLUGIN_DIR . '/', '', __FILE__ );\n if ( $plugins = get_option( 'active_plugins' ) ) {\n if ( $key = array_search( $path, $plugins ) ) {\n array_splice( $plugins, $key, 1 );\n array_unshift( $plugins, $path );\n update_option( 'active_plugins', $plugins );\n }\n }\n}\n</code></pre>\n\n<p>Place this function in your plugin and it will re-order the array so that your plugin is loaded first.</p></li>\n</ol>\n\n<p>The other option that you have is to omit the <code>if( function_exists())</code> statement when you declare your version of the function. If you do that, and someone else has plugged that function then php will exit with a fatal error \"function already exists\". This will have the effect of preventing someone else from plugging the function but it will also prevent the site from loading so I doubt that is a viable option for you.</p>\n"
},
{
"answer_id": 220235,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>Just needed to create a little comment in here. Pluggable functions are introduced in early days of WordPress (version 1.5.1) when we had just a few plugins. Nowadays, when many plugins may use the same function (say: <code>wp_mail</code>) we are in trouble.</p>\n\n<p>I found <a href=\"https://wpaxl.com/pluggable-functions-suck/\" rel=\"nofollow\">this blog article</a> has the point. What he suggested as a solution to pluggable functions is to use filters. He called the method <strong>short circuiting</strong>, where instead of this: </p>\n\n<pre><code>if ( ! function_exists( 'f1' ) ){\nfunction f1( $name ) {\n echo 'Hello ' . $name;\n}\n}\n</code></pre>\n\n<p>you would have :</p>\n\n<pre><code>function f1( $name ) { \n $pre = apply_filters( 'f1', false, $name ); \n if ( false !== $pre ) {\n echo $pre;\n return;\n } \n echo 'Hello ' . $name;\n}\n</code></pre>\n\n<hr>\n\n<p>Great, but I can imagine the solution not even using the pluggable function. You simple copy/paste the code from the pluggable function to your new plugin function that has different name/class and you are done. </p>\n\n<p>Of course, if the pluggable function ever changes you simple release the new plugin version.</p>\n"
}
] |
2015/07/15
|
[
"https://wordpress.stackexchange.com/questions/194634",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75547/"
] |
I just not only want to override a `pluggable function` (`wp_new_user_notification`) but I want to make sure that if any other plugin is overriding the same function, so my function , override that too or I want my overridden function to work instead of other plugin that is overriding the same function (`wp_new_user_notification`). May be a silly question but can I do it ??
|
The short answer to your question is yes; however, the methods to do this are a little bit hacky and generally I would recommend against all of them unless absolutely necessary.
Since `pluggable functions` actually replace the stock function by way of `function_exists()` whichever plugin that "plugs" the function first will win. What you want to do is ensure your plugin loads first globally.
Plugins are loaded according to their order in an array stored in the `wp_options` table. This array is sorted alphabetically. Knowing that, you have 2 options.
1. **Make it very likely that your plugin is alphabetically first.** I ***believe*** that `@` is considered alphabetically first in php, so if you start your plugin name with something like `@@MyPlugin` then it should get loaded first.
2. **Change the order of the array stored in the database using the `activated_plugin` hook.** I did a quick google search and found that someone had already written a function [here](http://snippets.khromov.se/modify-wordpress-plugin-load-order/). I've re-posted it below in case the link goes dead.
```
add_action( 'activated_plugin', 'my_plugin_load_first' );
function my_plugin_load_first(){
$path = str_replace( WP_PLUGIN_DIR . '/', '', __FILE__ );
if ( $plugins = get_option( 'active_plugins' ) ) {
if ( $key = array_search( $path, $plugins ) ) {
array_splice( $plugins, $key, 1 );
array_unshift( $plugins, $path );
update_option( 'active_plugins', $plugins );
}
}
}
```
Place this function in your plugin and it will re-order the array so that your plugin is loaded first.
The other option that you have is to omit the `if( function_exists())` statement when you declare your version of the function. If you do that, and someone else has plugged that function then php will exit with a fatal error "function already exists". This will have the effect of preventing someone else from plugging the function but it will also prevent the site from loading so I doubt that is a viable option for you.
|
194,635 |
<p>I have a simple loop but it returns it in any order. What I'm looking for is to alphabetize the loop. I've tried a few different things but Can't seem to get it to work.</p>
<pre><code><?php
// Start the loop.
while ( have_posts() ) : the_post();
// Include the page content template.
get_template_part( 'content', 'grid-projects' );
// End the loop.
endwhile;
?>
</code></pre>
|
[
{
"answer_id": 194642,
"author": "leendertvb",
"author_id": 27308,
"author_profile": "https://wordpress.stackexchange.com/users/27308",
"pm_score": 2,
"selected": false,
"text": "<p>You have to alter the query and add the <code>orderby</code> argument specified as <code>name</code>. I would go for the <code>pre_get_posts</code> action (<a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow\">see documentation</a>) with some conditional tags to select the query for the right page.</p>\n\n<p>For example:</p>\n\n<pre><code>function change_posts_order($query) {\n if($query->is_home() && $query->is_main_query()) { // edit to match the desired page\n $query->set('orderby', 'name');\n $query->set('order', 'ASC');\n }\n}\nadd_action('pre_get_posts', 'change_posts_order');\n</code></pre>\n"
},
{
"answer_id": 194704,
"author": "Oscar Arango",
"author_id": 54451,
"author_profile": "https://wordpress.stackexchange.com/users/54451",
"pm_score": 1,
"selected": true,
"text": "<p>this is what worked for me. works a treat.</p>\n\n<pre><code>$child_pages = new WP_Query( array(\n 'orderby' => 'name',\n 'order' => 'ASC',\n 'cat' => '41'\n) );\nwhile ( $child_pages->have_posts() ) : $child_pages->the_post();\n get_template_part( 'content', 'grid-projects' );\nendwhile;\nwp_reset_postdata();\n</code></pre>\n"
}
] |
2015/07/15
|
[
"https://wordpress.stackexchange.com/questions/194635",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54451/"
] |
I have a simple loop but it returns it in any order. What I'm looking for is to alphabetize the loop. I've tried a few different things but Can't seem to get it to work.
```
<?php
// Start the loop.
while ( have_posts() ) : the_post();
// Include the page content template.
get_template_part( 'content', 'grid-projects' );
// End the loop.
endwhile;
?>
```
|
this is what worked for me. works a treat.
```
$child_pages = new WP_Query( array(
'orderby' => 'name',
'order' => 'ASC',
'cat' => '41'
) );
while ( $child_pages->have_posts() ) : $child_pages->the_post();
get_template_part( 'content', 'grid-projects' );
endwhile;
wp_reset_postdata();
```
|
194,706 |
<p>I need to display max 5 latest sticky posts that have a thumbnail. And I need to have accurate counting of the displayed posts. I've tried to exclude sticky posts without a thumbnail with meta_query, but with no luck.</p>
<pre><code>$sticky = get_option('sticky_posts');
if (empty($sticky)) {
return;
}
$counter = 1;
$r = new WP_Query(array(
'posts_per_page' => 5,
'post__in' => $sticky,
'meta_query' => array(
array(
'key' => '_thumbnail_id',
'compare' => 'EXISTS',
),
),
'post_status' => 'publish',
'orderby' => 'post__in',
'post_type' => array( 'post' ),
));
if ($r->have_posts()) :
echo '<section class="header-sticky-posts '.$post_count.'">';
while ( $r->have_posts() ) : $r->the_post();
echo '<div class="header-sticky-post">';
// Post content
echo '</div>';
$counter++;
endwhile;
echo '</section>';
endif;
wp_reset_postdata();
</code></pre>
|
[
{
"answer_id": 194709,
"author": "Puni",
"author_id": 75322,
"author_profile": "https://wordpress.stackexchange.com/users/75322",
"pm_score": 0,
"selected": false,
"text": "<p>What you are doing is right except that you are careless or you just copied code from somewhere else and pasted in without modifying it. </p>\n\n<pre><code><?php\n$sticky = get_option('sticky_posts');\n\nif (empty($sticky)) {\n return;\n}\n\n$counter = 1;\n\n$posts = new WP_Query(array(\n 'posts_per_page' => 5,\n 'post__in' => $sticky,\n 'meta_query' => array(\n array(\n 'key' => '_thumbnail_id',\n 'compare' => 'EXISTS',\n ),\n ),\n 'post_status' => 'publish',\n 'orderby' => 'post__in',\n 'post_type' => array( 'post' ),\n));\n\n\nif ($posts->have_posts()) :\n\n while ( $posts->have_posts() ) : $posts->the_post();\n\n if ( has_post_thumbnail() ) :\n echo '<section class=\"header-sticky-posts'.$counter.'\">';\n echo '<div class=\"header-sticky-post\">';\n the_post_thumbnail();\n echo '</div>';\n echo '</section>';\n $counter++; \n endif;\n\n endwhile;\n\nendif;\nwp_reset_postdata();\n</code></pre>\n"
},
{
"answer_id": 194715,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>You need to set <code>ignore_sticky_posts</code> to <code>true</code> in your query arguments. This way you exclude sticky posts and only focus on the post ID's array being passed to <code>post_in</code></p>\n\n<pre><code>'ignore_sticky_posts' => true,\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>If this does not make much sense, please see <a href=\"https://wordpress.stackexchange.com/a/192253/31545\">my answer here</a> to similar question where I have explained it a bit better. Be sure to check it out</p>\n\n<h2>THE CODE</h2>\n\n<pre><code>$r = new WP_Query(array(\n 'posts_per_page' => 5,\n 'post__in' => $sticky,\n 'meta_query' => array(\n array(\n 'key' => '_thumbnail_id',\n 'compare' => 'EXISTS',\n ),\n ),\n 'post_status' => 'publish',\n 'orderby' => 'post__in',\n 'post_type' => array( 'post' ),\n 'ignore_sticky_posts' => true,\n));\n</code></pre>\n"
}
] |
2015/07/16
|
[
"https://wordpress.stackexchange.com/questions/194706",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31277/"
] |
I need to display max 5 latest sticky posts that have a thumbnail. And I need to have accurate counting of the displayed posts. I've tried to exclude sticky posts without a thumbnail with meta\_query, but with no luck.
```
$sticky = get_option('sticky_posts');
if (empty($sticky)) {
return;
}
$counter = 1;
$r = new WP_Query(array(
'posts_per_page' => 5,
'post__in' => $sticky,
'meta_query' => array(
array(
'key' => '_thumbnail_id',
'compare' => 'EXISTS',
),
),
'post_status' => 'publish',
'orderby' => 'post__in',
'post_type' => array( 'post' ),
));
if ($r->have_posts()) :
echo '<section class="header-sticky-posts '.$post_count.'">';
while ( $r->have_posts() ) : $r->the_post();
echo '<div class="header-sticky-post">';
// Post content
echo '</div>';
$counter++;
endwhile;
echo '</section>';
endif;
wp_reset_postdata();
```
|
You need to set `ignore_sticky_posts` to `true` in your query arguments. This way you exclude sticky posts and only focus on the post ID's array being passed to `post_in`
```
'ignore_sticky_posts' => true,
```
EDIT
----
If this does not make much sense, please see [my answer here](https://wordpress.stackexchange.com/a/192253/31545) to similar question where I have explained it a bit better. Be sure to check it out
THE CODE
--------
```
$r = new WP_Query(array(
'posts_per_page' => 5,
'post__in' => $sticky,
'meta_query' => array(
array(
'key' => '_thumbnail_id',
'compare' => 'EXISTS',
),
),
'post_status' => 'publish',
'orderby' => 'post__in',
'post_type' => array( 'post' ),
'ignore_sticky_posts' => true,
));
```
|
194,792 |
<p>In the media tab, upload of a valid image file results in display of "HTTP error".</p>
<p>Reload of the media tab shows that the image did upload and resize, though.</p>
<p>Browser debug tools show that on upload, browser is making a POST to wp-admin/async-upload.php. The server responds with a 500 error. The body of the response, though, is suspicious. The first part is a JSON structure. The JSON structure is immediately followed by an HTML document with the title "Wordpress Error" but an empty body.</p>
<p>Nothing going into the webserver (apache) error log and WP debug mode and increased PHP error/warning verbosity has not been helpful. Disabling all plugins had no effect on the error. Tried switching between GD and ImageMagick also with no success.</p>
<p>Relevant software versions:</p>
<ul>
<li>Wordpress 4.2.2.</li>
<li>PHP 5.5.12-2ubuntu4.4.</li>
<li>Ubuntu Utopic</li>
</ul>
<p>Any ideas on what might cause async-upload.php to return both JSON and an HTML error document and/or how I might further debug this?</p>
|
[
{
"answer_id": 195108,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 1,
"selected": false,
"text": "<p>This likely isn't exactly an issue caused by WordPress, but due to server configurations and/or settings. 500 errors are pretty generic and can have a variety of origins, so it is hard to give the one directive that will solve it. By the way, the returning of JSON and HTML seems to be common when this happens, not sure where and it gets mixed up, might be <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-admin/async-upload.php#L89\" rel=\"nofollow\">here</a> . I'm fairly certain this happens due to some memory issue.</p>\n\n<p>Although it likely has to do with the memory, I can't know for sure, because there isn't enough information available to be 100% certain. So here is a little, not necessarily comprehensive, check list for you to process:</p>\n\n<ul>\n<li><em>memory limit</em> - your PHP memory might be just on the verge of being not enough, increase it; put <code>define( 'WP_MEMORY_LIMIT', '128MB' );</code> into <code>wp-config.php</code></li>\n<li><em>.htaccess</em> - corruption/issue; check it; possibly back it up and regenerate it </li>\n<li><em>PHP5</em> - some hosts had problems with that, although I haven't seen it some time; try putting <code>AddType x-mapp-php5 .php</code> into your <code>.htaccess</code></li>\n<li><em>file permissions</em> - make sure they are correct, if you are unsure, then re-set them up with the correct ones; codex article: <a href=\"https://codex.wordpress.org/Changing_File_Permissions\" rel=\"nofollow\">changing file permissions</a></li>\n<li><em>folder permissions</em> -- \n\n<ul>\n<li><em>WP</em> - check an if needed correct them; codex article: <a href=\"https://codex.wordpress.org/Changing_File_Permissions\" rel=\"nofollow\">changing file permissions</a></li>\n<li><em>server</em> - sometimes there are e.g. problems with the permissions of the temporary upload folder</li>\n</ul></li>\n<li><em>re-uploading WP core files</em> - although that shouldn't be necessary if the last two steps are done correctly, but sometimes there are other corruptions, so it might be an additional step to take</li>\n<li><em>apache setup</em> - make sure your apache is set up correctly on your server, so to your needs and actual requirements; e.g. one common culprit seems to be <code>mod_security</code> </li>\n<li><em>check WP custom code</em> - so what you wrote or been installing via plug-ins; you know the routine, test by deactivating and/or switching to default theme and so on</li>\n</ul>\n\n<p>All the list items are pretty much well known and documented, so you will, if needed, find more information out there. </p>\n\n<p>Last but not least, much success!</p>\n"
},
{
"answer_id": 195257,
"author": "Rares P.",
"author_id": 21370,
"author_profile": "https://wordpress.stackexchange.com/users/21370",
"pm_score": 0,
"selected": false,
"text": "<p>In the <strong>wp-config.php</strong> file (wordpress's root folder) you have to enable the debug.</p>\n\n<p>You have to set <strong>wp_debug</strong> to <strong>true</strong>.</p>\n\n<p>Change <strong>define('WP_DEBUG', false);</strong> to <strong>define('WP_DEBUG', true);</strong></p>\n\n<p>Save the file and refresh the browser (I suggest you to use ctrl+f5).</p>\n\n<p>You'll see all the errors.</p>\n"
},
{
"answer_id": 302587,
"author": "Jörn Schellhaas",
"author_id": 142943,
"author_profile": "https://wordpress.stackexchange.com/users/142943",
"pm_score": 3,
"selected": true,
"text": "<p>I had the same issue and did not find any information in my debug output.</p>\n\n<p>It worked out, that <code>DOING_AJAX</code> was not defined (I don't know why).</p>\n\n<p>Changing the beginning of <code>async-upload.php</code> from</p>\n\n<pre><code>if ( isset( $_REQUEST['action'] ) && 'upload-attachment' === $_REQUEST['action'] ) {\n define( 'DOING_AJAX', true );\n}\n</code></pre>\n\n<p>to</p>\n\n<pre><code>define( 'DOING_AJAX', true );\n</code></pre>\n\n<p>worked for me. Maybe I will have a deeper look and find the real root cause.</p>\n"
},
{
"answer_id": 321788,
"author": "Krzysztof Przygoda",
"author_id": 89088,
"author_profile": "https://wordpress.stackexchange.com/users/89088",
"pm_score": 0,
"selected": false,
"text": "<p>Im my case (WP v5.0), it was PHP version problem (PHP v5.4). Switching to PHP v7.2 solved this problem.</p>\n"
},
{
"answer_id": 356531,
"author": "Christopher",
"author_id": 154062,
"author_profile": "https://wordpress.stackexchange.com/users/154062",
"pm_score": 0,
"selected": false,
"text": "<p>I suggest checking the webserver's error log before poking around in the dark.</p>\n\n<p>In my case I found the following error message</p>\n\n<pre><code>2020/01/16 15:30:24 [error] 24844#24844: *206729 client intended to send too large body: 33962282 bytes, client: xxx.xxxx.xxx.xxx, server: example.com, request: \"POST /wp-admin/async-upload.php HTTP/2.0\", host: \"example.com\", referrer: \"https://example.com/\"\n</code></pre>\n\n<p>Which simply means that nginx' <code>client_max_body_size</code> was too low. WordPress only checks <code>upload_max_filesize</code> in php configuration so WordPress allows to upload larger files than <code>client_max_body_size</code> if that value is lower than <code>upload_max_filesize</code>.</p>\n"
},
{
"answer_id": 406804,
"author": "sharulhafiz",
"author_id": 24533,
"author_profile": "https://wordpress.stackexchange.com/users/24533",
"pm_score": 0,
"selected": false,
"text": "<p>I solved this by increasing <a href=\"http://php.net/manual/ini.core.php#ini.post-max-size\" rel=\"nofollow noreferrer\">post_max_size</a> from 8MB to 16MB</p>\n"
}
] |
2015/07/17
|
[
"https://wordpress.stackexchange.com/questions/194792",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76335/"
] |
In the media tab, upload of a valid image file results in display of "HTTP error".
Reload of the media tab shows that the image did upload and resize, though.
Browser debug tools show that on upload, browser is making a POST to wp-admin/async-upload.php. The server responds with a 500 error. The body of the response, though, is suspicious. The first part is a JSON structure. The JSON structure is immediately followed by an HTML document with the title "Wordpress Error" but an empty body.
Nothing going into the webserver (apache) error log and WP debug mode and increased PHP error/warning verbosity has not been helpful. Disabling all plugins had no effect on the error. Tried switching between GD and ImageMagick also with no success.
Relevant software versions:
* Wordpress 4.2.2.
* PHP 5.5.12-2ubuntu4.4.
* Ubuntu Utopic
Any ideas on what might cause async-upload.php to return both JSON and an HTML error document and/or how I might further debug this?
|
I had the same issue and did not find any information in my debug output.
It worked out, that `DOING_AJAX` was not defined (I don't know why).
Changing the beginning of `async-upload.php` from
```
if ( isset( $_REQUEST['action'] ) && 'upload-attachment' === $_REQUEST['action'] ) {
define( 'DOING_AJAX', true );
}
```
to
```
define( 'DOING_AJAX', true );
```
worked for me. Maybe I will have a deeper look and find the real root cause.
|
194,812 |
<p>Ive got the following code for a WordPRess plugin that essentially add two custom inputs on each page/post edit screen. The values are then saved and output in the header of the frontend page.</p>
<p>The code works fine if it is located inside a .php file and dropped straight into 'wp-content/plugins'. However, if I put it in its own folder inside plugins eg 'wp-content/plugins/myplugin' the input fields are not saved when saving the post/page via the edit screen. Additionally nothing it output to the frontend pages html head section.</p>
<p>It seems like this is an abandoned project so Ive been unable to work with the original developer to work out a solution. However, it would certainly seem that by something in the code needs to be updated to reflect that the code is placed insicde a plugin folder.</p>
<p>Heres the code.....</p>
<pre><code><?php
$clinical_post_types = array();
//add all post types
$post_types = get_post_types();
foreach ( $post_types as $post_type ) {
$clinical_post_types[] = $post_type;
//echo 'POST TYPES: ' .$post_type;
}
// Meta box
// -----------------------------------------------------------------
// Add the language metabox on every registered custom post type
function clinical_add_language_metaboxe() {
global $clinical_post_types;
foreach ($clinical_post_types as $post_type) {
add_meta_box('clinical_meta_box', __('Search Engine Optimization', 'clinical'), 'clinical_meta_custom_box', $post_type, 'normal', 'default');
}
}
// The Post's meta fields Metabox
function clinical_meta_custom_box() {
global $post;
echo '<input type="hidden" name="clinicalmeta_noncename" '
. 'id="clinicalmeta_noncename" value="'
. wp_create_nonce( plugin_basename(__FILE__) ) . '/seo_fields.php" />';
// Get the meta fields data if its already been entered
$meta_title = get_post_meta($post->ID, '_clinical_meta_title', true);
$meta_description = get_post_meta($post->ID, '_clinical_meta_description', true);
// Echo out the field
$html = '<p><label for="clinical_meta_title"><strong>'. __('Title', 'clinical') .'</strong></label></p>';
$html .= '<p><input type="text" class="regular-text" name="_clinical_meta_title" id="clinical_meta_title" value="'. $meta_title .'" /></p>';
$html .= '<p><label for="clinical_meta_description"><strong>'. __('Description', 'clinical') .'</strong></label></p>';
$html .= '<p><textarea class="large-text" name="_clinical_meta_description" id="clinical_meta_description">'. $meta_description .'</textarea></p>';
echo $html;
}
// Save the metabox data
function clinical_save_post_meta($post_id, $post) {
global $clinical_post_types;
$key_title = '_clinical_meta_title';
$key_description = '_clinical_meta_description';
// if we're not in a clinical-enabled post type, skip.
if (in_array($post->post_type, $clinical_post_types))
return $post;
// verify this came from our screen and with proper authorization,
// because save_post can be triggered at other times
if ((empty($_POST[$key_title]) && empty($_POST[$key_description])) || empty($_POST['clinicalmeta_noncename']) || !wp_verify_nonce($_POST['clinicalmeta_noncename'], plugin_basename(__FILE__).'/seo_fields.php')
|| !current_user_can('edit_post', $post->ID)
) {
return $post->ID;
}
// OK, we're authenticated: we need to find and save the data
$title = $_POST[$key_title];
$description = $_POST[$key_description];
// set the post's meta title:
$updated_title = update_post_meta($post->ID, $key_title, $title);
$updated_description = update_post_meta($post->ID, $key_description, $description);
// Delete if blank:
if (!$title) delete_post_meta($post->ID, $key_title);
if (!$description) delete_post_meta($post->ID, $key_description);
}
// Filters
function clinical_wp_title_filter($title) {
global $post;
$seo_title = get_post_meta($post->ID, '_clinical_meta_title', true);
if (!empty($seo_title))
return $seo_title;
return $title;
}
function clinical_wp_head_action() {
global $post;
$seo_description = get_post_meta($post->ID, '_clinical_meta_description', true);
if (!empty($seo_description)) {
echo '<!-- Clinical CMS SEO -->
<meta name="description" content="'. esc_attr($seo_description) .'" />
<!-- END Clinical CMS SEO -->';
}
}
// Helpers
// Filters and Hooks
add_action('admin_init', 'clinical_add_language_metaboxe');
add_action('save_post', 'clinical_save_post_meta', 1, 2);
add_filter('wp_title', 'clinical_wp_title_filter');
add_action('wp_head', 'clinical_wp_head_action');
</code></pre>
|
[
{
"answer_id": 195592,
"author": "Subharanjan",
"author_id": 13615,
"author_profile": "https://wordpress.stackexchange.com/users/13615",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the fixed and modified code which was having the nonce action issue.</p>\n\n<pre><code><?php\n/*\nPlugin Name: Test Plugin\nPlugin URI: Test\nDescription: Test\nAuthor: Test\nVersion: 007\nAuthor URI:\n*/\n\n// add all post types\n$clinical_post_types = array();\n$post_types = get_post_types();\nforeach ( $post_types as $post_type ) {\n $clinical_post_types[] = $post_type;\n}\n\n// Meta box\n// Add the language metabox on every registered custom post type\nfunction clinical_add_language_metaboxe() {\n global $clinical_post_types;\n foreach ( $clinical_post_types as $post_type ) {\n add_meta_box( 'clinical_meta_box', __( 'Search Engine Optimization', 'clinical' ), 'clinical_meta_custom_box', $post_type, 'normal', 'default' );\n }\n}\n\n// The Post's meta fields Metabox\nfunction clinical_meta_custom_box() {\n global $post;\n\n // Get the meta fields data if its already been entered\n $meta_title = get_post_meta( $post->ID, '_clinical_meta_title', true );\n $meta_description = get_post_meta( $post->ID, '_clinical_meta_description', true );\n\n echo '<input type=\"hidden\" name=\"clinicalmeta_noncename\" id=\"clinicalmeta_noncename\" value=\"' . wp_create_nonce( \"clinicalmeta_nonce_action\" ) . '\" />';\n\n // Echo out the field\n $html = '<p><label for=\"clinical_meta_title\"><strong>' . __( 'Title', 'clinical' ) . '</strong></label></p>';\n $html .= '<p><input type=\"text\" class=\"regular-text\" name=\"_clinical_meta_title\" id=\"clinical_meta_title\" value=\"' . $meta_title . '\" /></p>';\n $html .= '<p><label for=\"clinical_meta_description\"><strong>' . __( 'Description', 'clinical' ) . '</strong></label></p>';\n $html .= '<p><textarea class=\"large-text\" name=\"_clinical_meta_description\" id=\"clinical_meta_description\">' . $meta_description . '</textarea></p>';\n echo $html;\n}\n\n// Save the metabox data\nfunction clinical_save_post_meta( $post_id, $post ) {\n global $clinical_post_types;\n\n $key_title = '_clinical_meta_title';\n $key_description = '_clinical_meta_description';\n\n // if we're not in a clinical-enabled post type, skip.\n if ( in_array( $post->post_type, $clinical_post_types ) ) {\n // return $post;\n }\n // verify this came from our screen and with proper authorization,\n // because save_post can be triggered at other times\n if ( ( empty( $_POST[ $key_title ] ) && empty( $_POST[ $key_description ] ) ) || empty( $_POST['clinicalmeta_noncename'] ) || ( ! wp_verify_nonce( $_POST['clinicalmeta_noncename'], \"clinicalmeta_nonce_action\" ) ) || ( ! current_user_can( 'edit_post', $post->ID ) ) ) {\n return $post->ID;\n }\n // OK, we're authenticated: we need to find and save the data\n $title = $_POST[ $key_title ];\n $description = $_POST[ $key_description ];\n\n // set the post's meta title:\n $updated_title = update_post_meta( $post->ID, $key_title, $title );\n $updated_description = update_post_meta( $post->ID, $key_description, $description );\n // Delete if blank:\n if ( empty( $title ) ) {\n delete_post_meta( $post->ID, $key_title );\n }\n if ( empty( $description ) ) {\n delete_post_meta( $post->ID, $key_description );\n }\n}\n\n// Filters\nfunction clinical_wp_title_filter( $title ) {\n global $post;\n $seo_title = get_post_meta( $post->ID, '_clinical_meta_title', true );\n if ( ! empty( $seo_title ) ) {\n return $seo_title;\n }\n\n return $title;\n}\n\nfunction clinical_wp_head_action() {\n global $post;\n $seo_description = get_post_meta( $post->ID, '_clinical_meta_description', true );\n if ( ! empty( $seo_description ) ) {\n echo '<!-- Clinical CMS SEO --> <meta name=\"description\" content=\"' . esc_attr( $seo_description ) . '\" /> <!-- END Clinical CMS SEO -->';\n }\n}\n\n// Helpers\n// Filters and Hooks\nadd_action( 'admin_init', 'clinical_add_language_metaboxe' );\nadd_action( 'save_post', 'clinical_save_post_meta', 1, 2 );\nadd_filter( 'wp_title', 'clinical_wp_title_filter' );\nadd_action( 'wp_head', 'clinical_wp_head_action' );\n</code></pre>\n"
},
{
"answer_id": 195874,
"author": "Hendrik Luehrsen",
"author_id": 38514,
"author_profile": "https://wordpress.stackexchange.com/users/38514",
"pm_score": 1,
"selected": false,
"text": "<p>This is an issue with the creation of the nonce. </p>\n\n<pre><code>wp_create_nonce( plugin_basename(__FILE__) ) . '/seo_fields.php\" />\n</code></pre>\n\n<p>should probably be</p>\n\n<pre><code>wp_create_nonce( plugin_basename(__FILE__) . '/seo_fields.php' ) . '\" />\n</code></pre>\n\n<p>because otherwise</p>\n\n<pre><code>!wp_verify_nonce($_POST['clinicalmeta_noncename'], plugin_basename(__FILE__).'/seo_fields.php')\n</code></pre>\n\n<p>would not check for the same action. </p>\n\n<p>See: <a href=\"https://codex.wordpress.org/Function_Reference/wp_verify_nonce#Parameters\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_verify_nonce#Parameters</a></p>\n\n<p><em>drops mic</em></p>\n"
}
] |
2015/07/17
|
[
"https://wordpress.stackexchange.com/questions/194812",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/55152/"
] |
Ive got the following code for a WordPRess plugin that essentially add two custom inputs on each page/post edit screen. The values are then saved and output in the header of the frontend page.
The code works fine if it is located inside a .php file and dropped straight into 'wp-content/plugins'. However, if I put it in its own folder inside plugins eg 'wp-content/plugins/myplugin' the input fields are not saved when saving the post/page via the edit screen. Additionally nothing it output to the frontend pages html head section.
It seems like this is an abandoned project so Ive been unable to work with the original developer to work out a solution. However, it would certainly seem that by something in the code needs to be updated to reflect that the code is placed insicde a plugin folder.
Heres the code.....
```
<?php
$clinical_post_types = array();
//add all post types
$post_types = get_post_types();
foreach ( $post_types as $post_type ) {
$clinical_post_types[] = $post_type;
//echo 'POST TYPES: ' .$post_type;
}
// Meta box
// -----------------------------------------------------------------
// Add the language metabox on every registered custom post type
function clinical_add_language_metaboxe() {
global $clinical_post_types;
foreach ($clinical_post_types as $post_type) {
add_meta_box('clinical_meta_box', __('Search Engine Optimization', 'clinical'), 'clinical_meta_custom_box', $post_type, 'normal', 'default');
}
}
// The Post's meta fields Metabox
function clinical_meta_custom_box() {
global $post;
echo '<input type="hidden" name="clinicalmeta_noncename" '
. 'id="clinicalmeta_noncename" value="'
. wp_create_nonce( plugin_basename(__FILE__) ) . '/seo_fields.php" />';
// Get the meta fields data if its already been entered
$meta_title = get_post_meta($post->ID, '_clinical_meta_title', true);
$meta_description = get_post_meta($post->ID, '_clinical_meta_description', true);
// Echo out the field
$html = '<p><label for="clinical_meta_title"><strong>'. __('Title', 'clinical') .'</strong></label></p>';
$html .= '<p><input type="text" class="regular-text" name="_clinical_meta_title" id="clinical_meta_title" value="'. $meta_title .'" /></p>';
$html .= '<p><label for="clinical_meta_description"><strong>'. __('Description', 'clinical') .'</strong></label></p>';
$html .= '<p><textarea class="large-text" name="_clinical_meta_description" id="clinical_meta_description">'. $meta_description .'</textarea></p>';
echo $html;
}
// Save the metabox data
function clinical_save_post_meta($post_id, $post) {
global $clinical_post_types;
$key_title = '_clinical_meta_title';
$key_description = '_clinical_meta_description';
// if we're not in a clinical-enabled post type, skip.
if (in_array($post->post_type, $clinical_post_types))
return $post;
// verify this came from our screen and with proper authorization,
// because save_post can be triggered at other times
if ((empty($_POST[$key_title]) && empty($_POST[$key_description])) || empty($_POST['clinicalmeta_noncename']) || !wp_verify_nonce($_POST['clinicalmeta_noncename'], plugin_basename(__FILE__).'/seo_fields.php')
|| !current_user_can('edit_post', $post->ID)
) {
return $post->ID;
}
// OK, we're authenticated: we need to find and save the data
$title = $_POST[$key_title];
$description = $_POST[$key_description];
// set the post's meta title:
$updated_title = update_post_meta($post->ID, $key_title, $title);
$updated_description = update_post_meta($post->ID, $key_description, $description);
// Delete if blank:
if (!$title) delete_post_meta($post->ID, $key_title);
if (!$description) delete_post_meta($post->ID, $key_description);
}
// Filters
function clinical_wp_title_filter($title) {
global $post;
$seo_title = get_post_meta($post->ID, '_clinical_meta_title', true);
if (!empty($seo_title))
return $seo_title;
return $title;
}
function clinical_wp_head_action() {
global $post;
$seo_description = get_post_meta($post->ID, '_clinical_meta_description', true);
if (!empty($seo_description)) {
echo '<!-- Clinical CMS SEO -->
<meta name="description" content="'. esc_attr($seo_description) .'" />
<!-- END Clinical CMS SEO -->';
}
}
// Helpers
// Filters and Hooks
add_action('admin_init', 'clinical_add_language_metaboxe');
add_action('save_post', 'clinical_save_post_meta', 1, 2);
add_filter('wp_title', 'clinical_wp_title_filter');
add_action('wp_head', 'clinical_wp_head_action');
```
|
Here is the fixed and modified code which was having the nonce action issue.
```
<?php
/*
Plugin Name: Test Plugin
Plugin URI: Test
Description: Test
Author: Test
Version: 007
Author URI:
*/
// add all post types
$clinical_post_types = array();
$post_types = get_post_types();
foreach ( $post_types as $post_type ) {
$clinical_post_types[] = $post_type;
}
// Meta box
// Add the language metabox on every registered custom post type
function clinical_add_language_metaboxe() {
global $clinical_post_types;
foreach ( $clinical_post_types as $post_type ) {
add_meta_box( 'clinical_meta_box', __( 'Search Engine Optimization', 'clinical' ), 'clinical_meta_custom_box', $post_type, 'normal', 'default' );
}
}
// The Post's meta fields Metabox
function clinical_meta_custom_box() {
global $post;
// Get the meta fields data if its already been entered
$meta_title = get_post_meta( $post->ID, '_clinical_meta_title', true );
$meta_description = get_post_meta( $post->ID, '_clinical_meta_description', true );
echo '<input type="hidden" name="clinicalmeta_noncename" id="clinicalmeta_noncename" value="' . wp_create_nonce( "clinicalmeta_nonce_action" ) . '" />';
// Echo out the field
$html = '<p><label for="clinical_meta_title"><strong>' . __( 'Title', 'clinical' ) . '</strong></label></p>';
$html .= '<p><input type="text" class="regular-text" name="_clinical_meta_title" id="clinical_meta_title" value="' . $meta_title . '" /></p>';
$html .= '<p><label for="clinical_meta_description"><strong>' . __( 'Description', 'clinical' ) . '</strong></label></p>';
$html .= '<p><textarea class="large-text" name="_clinical_meta_description" id="clinical_meta_description">' . $meta_description . '</textarea></p>';
echo $html;
}
// Save the metabox data
function clinical_save_post_meta( $post_id, $post ) {
global $clinical_post_types;
$key_title = '_clinical_meta_title';
$key_description = '_clinical_meta_description';
// if we're not in a clinical-enabled post type, skip.
if ( in_array( $post->post_type, $clinical_post_types ) ) {
// return $post;
}
// verify this came from our screen and with proper authorization,
// because save_post can be triggered at other times
if ( ( empty( $_POST[ $key_title ] ) && empty( $_POST[ $key_description ] ) ) || empty( $_POST['clinicalmeta_noncename'] ) || ( ! wp_verify_nonce( $_POST['clinicalmeta_noncename'], "clinicalmeta_nonce_action" ) ) || ( ! current_user_can( 'edit_post', $post->ID ) ) ) {
return $post->ID;
}
// OK, we're authenticated: we need to find and save the data
$title = $_POST[ $key_title ];
$description = $_POST[ $key_description ];
// set the post's meta title:
$updated_title = update_post_meta( $post->ID, $key_title, $title );
$updated_description = update_post_meta( $post->ID, $key_description, $description );
// Delete if blank:
if ( empty( $title ) ) {
delete_post_meta( $post->ID, $key_title );
}
if ( empty( $description ) ) {
delete_post_meta( $post->ID, $key_description );
}
}
// Filters
function clinical_wp_title_filter( $title ) {
global $post;
$seo_title = get_post_meta( $post->ID, '_clinical_meta_title', true );
if ( ! empty( $seo_title ) ) {
return $seo_title;
}
return $title;
}
function clinical_wp_head_action() {
global $post;
$seo_description = get_post_meta( $post->ID, '_clinical_meta_description', true );
if ( ! empty( $seo_description ) ) {
echo '<!-- Clinical CMS SEO --> <meta name="description" content="' . esc_attr( $seo_description ) . '" /> <!-- END Clinical CMS SEO -->';
}
}
// Helpers
// Filters and Hooks
add_action( 'admin_init', 'clinical_add_language_metaboxe' );
add_action( 'save_post', 'clinical_save_post_meta', 1, 2 );
add_filter( 'wp_title', 'clinical_wp_title_filter' );
add_action( 'wp_head', 'clinical_wp_head_action' );
```
|
194,840 |
<p>I have created a page where user can see his favourite post which has been bookmarked by him </p>
<pre><code>get_user_favorites($user_id);
</code></pre>
<p>This function is responsible for returning me all the favourite posts bookmarked by user in an array.</p>
<p>I am using this approach to get the data from the database and make it work inside my Custom Html.</p>
<pre><code> <?php $user_fav = get_user_favorites($user_id);
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
'posts_per_page' => 4,
'post_type' => array('communityposts','post','video'),
'post__in' => $user_fav,
'post_status' => 'publish',
'suppress_filters' => true ,
'paged' => $paged
);
$posts_array = get_posts( $args );
foreach ($posts_array as $p) :
?>
<article class="post-items-latest">
<a href="<?php echo get_permalink( $p->ID ); ?>" title="<?php echo $p->post_title; ?>">
<span class="image-wrapper">
<?php
$thumb = get_post_thumbnail_id($p->ID);
$img_url = wp_get_attachment_url( $thumb,'full' ); //get full URL to image (use "large" or "medium" if the images too big)
?>
<img src="<?php echo $img_url; ?>" alt="<?php $p->post_title; ?>" width="226" height="117">
</span>
<h1><?php echo $p->post_title; ?></h1>
</a>
<div class="post-footer">
<span class="user"><i class="fa fa-user"></i>&nbsp;<?php echo get_the_author_link(); ?></span>
<span class="data"><i class="fa fa-clock-o"></i>&nbsp;<?php wp_days_ago_v3(); ?></span>
<span class="likes"><i class="fa fa-eye"></i>&nbsp;<?php echo $meta_values = get_post_meta( get_the_ID(), 'cv_post_views_count', true ); ?> </span>
</div>
</article>
<?php endforeach; ?>
<div class="post-nav-container">
<?php previous_posts_link( __('&rarr; Older Posts','circoviral')); ?>
<?php next_posts_link( __('&larr; Older Posts','circoviral')); ?>
</div>
</code></pre>
<p>Using this approach i am able to get the Favourited post by an User but i am not able to make the <code>next_posts_link();</code> and <code>previous_posts_link();</code> work inside my template</p>
<p>Is there anything i am doing wrong ?</p>
|
[
{
"answer_id": 194850,
"author": "terminator",
"author_id": 55034,
"author_profile": "https://wordpress.stackexchange.com/users/55034",
"pm_score": 1,
"selected": false,
"text": "<p>Harman, don't use <code>get_posts()</code> when <code>pagination is required</code>. You may also accomplish this task using <code>WP_Query</code>. </p>\n\n<p>Refer to this answer explained beautifully by Chip Bennett at</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/120407/how-to-fix-pagination-for-custom-loops\">How to fix pagination for custom loops?</a></p>\n\n<pre><code> <?php $user_fav = get_user_favorites($user_id); \n $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;\n $args = array(\n 'posts_per_page' => 4,\n 'post_type' => array('communityposts','post','video'),\n 'post__in' => $user_fav,\n 'post_status' => 'publish',\n 'suppress_filters' => true ,\n 'paged' => $paged\n );\n $loop = new WP_Query( $args );\n $temp_query = $wp_query;\n $wp_query = NULL;\n $wp_query = $loop;\n if( $loop->have_posts()):while($loop->have_posts()):$loop->the_post(); \n ?>\n\n<article class=\"post-items-latest\">\n <a href=\"<?php echo get_permalink( $post->ID ); ?>\" title=\"<?php the_title(); ?>\">\n <span class=\"image-wrapper\">\n\n <?php\n $thumb = get_post_thumbnail_id($post->ID);\n $img_url = wp_get_attachment_url( $thumb,'full' ); //get full URL to image (use \"large\" or \"medium\" if the images too big)\n ?>\n <img src=\"<?php echo $img_url; ?>\" alt=\"<?php the_title(); ?>\" width=\"226\" height=\"117\">\n\n </span>\n <h1><?php the_title(); ?></h1>\n </a>\n <div class=\"post-footer\">\n <span class=\"user\"><i class=\"fa fa-user\"></i>&nbsp;<?php echo get_the_author_link(); ?></span>\n <span class=\"data\"><i class=\"fa fa-clock-o\"></i>&nbsp;<?php wp_days_ago_v3(); ?></span>\n <span class=\"likes\"><i class=\"fa fa-eye\"></i>&nbsp;<?php echo $meta_values = get_post_meta( get_the_ID(), 'cv_post_views_count', true ); ?> </span>\n </div>\n</article>\n\n<?php \nendwhile;\nendif;\nwp_reset_postdata();\n?>\n\n<div class=\"post-nav-container\">\n <?php previous_posts_link( __('&rarr; Older Posts')); ?>\n <?php next_posts_link( __('Newer Posts &larr; ',$loop->max_num_pages)); ?>\n</div>\n\n<?php \n$wp_query = NULL;\n$wp_query = $temp_query;\n?>\n</code></pre>\n"
},
{
"answer_id": 194995,
"author": "Harman Preet",
"author_id": 56650,
"author_profile": "https://wordpress.stackexchange.com/users/56650",
"pm_score": 1,
"selected": true,
"text": "<p>My approach was also correct but the only problem was we were missing is that resetting the query before the post navigation links. </p>\n\n<p>Here is the updated answer.</p>\n\n<pre><code> <?php $user_fav = get_user_favorites($user_id); \n $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;\n $args = array(\n 'posts_per_page' => 4,\n 'post_type' => array('communityposts','post','video'),\n 'post__in' => $user_fav,\n 'post_status' => 'publish',\n 'suppress_filters' => true,\n 'paged' => $paged,\n 'order_by' => 'date',\n 'order' => 'ASC' \n );\n $wp_query = new WP_Query( $args );\n\n if( $wp_query->have_posts()):while($wp_query->have_posts()):$wp_query->the_post();\n\n ?>\n\n <article class=\"post-items-latest\">\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title(); ?>\">\n <span class=\"image-wrapper\">\n\n <?php\n $thumb = get_post_thumbnail_id($post->ID);\n $img_url = wp_get_attachment_url( $thumb,'full' ); //get full URL to image (use \"large\" or \"medium\" if the images too big)\n $image = aq_resize( $img_url, 226, 117,true,true,true); //resize & crop the image\n ?>\n\n <?php if(!empty($image)): ?>\n <img src=\"<?php echo $image; ?>\" alt=\"<?php the_title(); ?>\" width=\"226\" height=\"117\">\n <?php else: ?>\n\n <?php if (has_post_thumbnail()): ?>\n\n <?php the_post_thumbnail( 'large'); ?>\n\n <?php endif; ?>\n <?php endif; ?>\n\n </span>\n <h1><?php the_title(); ?></h1>\n </a>\n <div class=\"post-footer\">\n <span class=\"user\"><i class=\"fa fa-user\"></i>&nbsp;<?php echo get_the_author_link(); ?></span>\n <span class=\"data\"><i class=\"fa fa-clock-o\"></i>&nbsp;<?php wp_days_ago_v3(); ?></span>\n <span class=\"likes\"><i class=\"fa fa-eye\"></i>&nbsp;<?php echo $meta_values = get_post_meta( get_the_ID(), 'cv_post_views_count', true ); ?> </span>\n </div>\n </article>\n\n <?php \n endwhile;\n endif;\n ?>\n\n <div class=\"post-nav-container\">\n <?php previous_posts_link( __('&rarr; Older Posts')); ?>\n <?php next_posts_link( __('Newer Posts &larr; ')); ?>\n </div>\n <?php wp_reset_query(); ?>\n</code></pre>\n"
}
] |
2015/07/17
|
[
"https://wordpress.stackexchange.com/questions/194840",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/56650/"
] |
I have created a page where user can see his favourite post which has been bookmarked by him
```
get_user_favorites($user_id);
```
This function is responsible for returning me all the favourite posts bookmarked by user in an array.
I am using this approach to get the data from the database and make it work inside my Custom Html.
```
<?php $user_fav = get_user_favorites($user_id);
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
'posts_per_page' => 4,
'post_type' => array('communityposts','post','video'),
'post__in' => $user_fav,
'post_status' => 'publish',
'suppress_filters' => true ,
'paged' => $paged
);
$posts_array = get_posts( $args );
foreach ($posts_array as $p) :
?>
<article class="post-items-latest">
<a href="<?php echo get_permalink( $p->ID ); ?>" title="<?php echo $p->post_title; ?>">
<span class="image-wrapper">
<?php
$thumb = get_post_thumbnail_id($p->ID);
$img_url = wp_get_attachment_url( $thumb,'full' ); //get full URL to image (use "large" or "medium" if the images too big)
?>
<img src="<?php echo $img_url; ?>" alt="<?php $p->post_title; ?>" width="226" height="117">
</span>
<h1><?php echo $p->post_title; ?></h1>
</a>
<div class="post-footer">
<span class="user"><i class="fa fa-user"></i> <?php echo get_the_author_link(); ?></span>
<span class="data"><i class="fa fa-clock-o"></i> <?php wp_days_ago_v3(); ?></span>
<span class="likes"><i class="fa fa-eye"></i> <?php echo $meta_values = get_post_meta( get_the_ID(), 'cv_post_views_count', true ); ?> </span>
</div>
</article>
<?php endforeach; ?>
<div class="post-nav-container">
<?php previous_posts_link( __('→ Older Posts','circoviral')); ?>
<?php next_posts_link( __('← Older Posts','circoviral')); ?>
</div>
```
Using this approach i am able to get the Favourited post by an User but i am not able to make the `next_posts_link();` and `previous_posts_link();` work inside my template
Is there anything i am doing wrong ?
|
My approach was also correct but the only problem was we were missing is that resetting the query before the post navigation links.
Here is the updated answer.
```
<?php $user_fav = get_user_favorites($user_id);
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
'posts_per_page' => 4,
'post_type' => array('communityposts','post','video'),
'post__in' => $user_fav,
'post_status' => 'publish',
'suppress_filters' => true,
'paged' => $paged,
'order_by' => 'date',
'order' => 'ASC'
);
$wp_query = new WP_Query( $args );
if( $wp_query->have_posts()):while($wp_query->have_posts()):$wp_query->the_post();
?>
<article class="post-items-latest">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<span class="image-wrapper">
<?php
$thumb = get_post_thumbnail_id($post->ID);
$img_url = wp_get_attachment_url( $thumb,'full' ); //get full URL to image (use "large" or "medium" if the images too big)
$image = aq_resize( $img_url, 226, 117,true,true,true); //resize & crop the image
?>
<?php if(!empty($image)): ?>
<img src="<?php echo $image; ?>" alt="<?php the_title(); ?>" width="226" height="117">
<?php else: ?>
<?php if (has_post_thumbnail()): ?>
<?php the_post_thumbnail( 'large'); ?>
<?php endif; ?>
<?php endif; ?>
</span>
<h1><?php the_title(); ?></h1>
</a>
<div class="post-footer">
<span class="user"><i class="fa fa-user"></i> <?php echo get_the_author_link(); ?></span>
<span class="data"><i class="fa fa-clock-o"></i> <?php wp_days_ago_v3(); ?></span>
<span class="likes"><i class="fa fa-eye"></i> <?php echo $meta_values = get_post_meta( get_the_ID(), 'cv_post_views_count', true ); ?> </span>
</div>
</article>
<?php
endwhile;
endif;
?>
<div class="post-nav-container">
<?php previous_posts_link( __('→ Older Posts')); ?>
<?php next_posts_link( __('Newer Posts ← ')); ?>
</div>
<?php wp_reset_query(); ?>
```
|
194,844 |
<p>I recently created a website at www.volatileinterface.com, using WordPress. I am using the cyanotype theme and I wanted to create a custom 404 error page for when a webpage could not be found. I edited 404.php to look like this.</p>
<pre><code> <?php
get_header(); ?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<div class="page-content">
<img src="/deadend.jpg"></img>
<p><?php _e( 'It looks like nothing was found at this location. Maybe try a search?', 'twentyfourteen' ); ?></p>
<?php get_search_form(); ?>
</div><!-- .page-content -->
</div><!-- #content -->
</div><!-- #primary -->
<?php
get_sidebar( 'content' );
get_sidebar();
get_footer();
</code></pre>
<p>When I go to a page that doesn't exist such as <a href="http://www.volatileinterface.com/index.php/jargon" rel="nofollow">http://www.volatileinterface.com/index.php/jargon</a> the website and 404 error page appear fine. However, when I go to a page like this <a href="http://www.volatileinterface.com/jargon" rel="nofollow">http://www.volatileinterface.com/jargon</a>
that does not have index.php in its address the broswer just goes to the default 404 error page. How do I always make the browser go to my custom 404 error page?</p>
|
[
{
"answer_id": 194845,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": true,
"text": "<p>WordPress doesn't receive those requests, so the server 404 displays. If you want WordPress to handle all 404s, use <code>mod_rewrite</code> Pretty Permalinks rather than <code>PATHINFO</code> permalinks. The requirements are detailed in <a href=\"https://codex.wordpress.org/Using_Permalinks\" rel=\"nofollow\">Using Permalinks</a>.</p>\n"
},
{
"answer_id": 194851,
"author": "Shakil Ahmed",
"author_id": 76359,
"author_profile": "https://wordpress.stackexchange.com/users/76359",
"pm_score": -1,
"selected": false,
"text": "<p>set a permalink structure on settings> permalinks . WordPress needs to create the .htaccess file. </p>\n"
}
] |
2015/07/17
|
[
"https://wordpress.stackexchange.com/questions/194844",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76345/"
] |
I recently created a website at www.volatileinterface.com, using WordPress. I am using the cyanotype theme and I wanted to create a custom 404 error page for when a webpage could not be found. I edited 404.php to look like this.
```
<?php
get_header(); ?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<div class="page-content">
<img src="/deadend.jpg"></img>
<p><?php _e( 'It looks like nothing was found at this location. Maybe try a search?', 'twentyfourteen' ); ?></p>
<?php get_search_form(); ?>
</div><!-- .page-content -->
</div><!-- #content -->
</div><!-- #primary -->
<?php
get_sidebar( 'content' );
get_sidebar();
get_footer();
```
When I go to a page that doesn't exist such as <http://www.volatileinterface.com/index.php/jargon> the website and 404 error page appear fine. However, when I go to a page like this <http://www.volatileinterface.com/jargon>
that does not have index.php in its address the broswer just goes to the default 404 error page. How do I always make the browser go to my custom 404 error page?
|
WordPress doesn't receive those requests, so the server 404 displays. If you want WordPress to handle all 404s, use `mod_rewrite` Pretty Permalinks rather than `PATHINFO` permalinks. The requirements are detailed in [Using Permalinks](https://codex.wordpress.org/Using_Permalinks).
|
194,849 |
<p>I am trying to add avatars to my wordpress web site and I activated them through the settings - discussion as you would normally do. But because I have a very customised theme, I guess, it is not working.</p>
<p>That is the code in my functions.php, where it shows the author and the comment, but not the avatar/gravatar:</p>
<pre><code>function mytheme_comment($comment, $args, $depth) {
$GLOBALS['comment'] = $comment; ?>
<li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
<div id="comment-<?php comment_ID(); ?>">
<div class="comment-author vcard">
<?php printf(__('%s <span class="says">:</span>'), get_comment_author_link()) ?><br />
<?php if ($comment->comment_approved == '0'): ?>
<em><?php _e('Your comment is awaiting moderation.') ?></em>
<br />
<?php endif; ?>
</div>
<div class="comment-meta commentmetadata"><a href="<?php echo esc_url( get_comment_link( $comment->comment_ID ) ) ?>">
<?php printf(__('%1$s, %2$s'), get_comment_date(), get_comment_time()) ?></a><?php edit_comment_link(__('(Edit)'),' ','') ?></div>
<?php comment_text() ?>
</code></pre>
<p>Here is an example how comments are shown right now: <a href="http://goo.gl/QkSzrd" rel="nofollow">http://goo.gl/QkSzrd</a></p>
<p>I believe, I have to build in get_avatar somewhere in the line before "get_author_link", but everything I did just lead to failure. Either it was just showing the "missing person" avatar (and not the ones connected to those commenting users) or it was deleting the author's name and showing nothing. :\</p>
<p>UPDATE:</p>
<p>Changing the line</p>
<pre><code> <?php printf(__('%s <span class="says">:</span>'), get_comment_author_link()) ?><br />
</code></pre>
<p>to</p>
<pre><code> <?php printf(__('%s <span class="says">:</span>'), get_avatar ($comment, '72')) ?><br />
</code></pre>
<p>brings up the avatar icon, I think, but it deletes the author/username of the comment and it places the avatar some place, I cannot understand (right side corner).</p>
<p>I can live with the right side corner, maybe it is just a CSS issue, <strong>but how do I get author/username of the comment back before the colon?</strong> In other words: I would like to have both, get_comment_author_link <strong>and</strong> the avatar.</p>
|
[
{
"answer_id": 194852,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": true,
"text": "<p>You're looking for the <code>get_avatar</code> function, <a href=\"https://codex.wordpress.org/Function_Reference/get_avatar\" rel=\"nofollow\">documented here</a></p>\n\n<pre><code>get_avatar( $id_or_email, $size, $default, $alt )\n</code></pre>\n\n<p>You'll need either a user ID, or an email to use it, something like this should do the trick:</p>\n\n<pre><code>echo get_avatar( get_comment_author_email(), 'thumbnail' );\n</code></pre>\n\n<p>If avatars are turned off in settings, this function will not return anything</p>\n"
},
{
"answer_id": 194865,
"author": "vega",
"author_id": 50311,
"author_profile": "https://wordpress.stackexchange.com/users/50311",
"pm_score": 0,
"selected": false,
"text": "<p>Alright, I just doubled it now by adding the avatar line before the author link. Both keep intact this way and get to be shown.</p>\n\n<p>Here is the code, I added/changed:</p>\n\n<pre><code><div class=\"comment-author vcard\">\n <?php echo get_avatar ($comment, '72'); ?>\n <?php printf(__('%s <span class=\"says\">:</span>'), get_comment_author_link()) ?><br />\n <?php if ($comment->comment_approved == '0'): ?>\n <em><?php _e('Your comment is awaiting moderation.') ?></em>\n <br />\n <?php endif; ?>\n</div>\n</code></pre>\n"
}
] |
2015/07/17
|
[
"https://wordpress.stackexchange.com/questions/194849",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/50311/"
] |
I am trying to add avatars to my wordpress web site and I activated them through the settings - discussion as you would normally do. But because I have a very customised theme, I guess, it is not working.
That is the code in my functions.php, where it shows the author and the comment, but not the avatar/gravatar:
```
function mytheme_comment($comment, $args, $depth) {
$GLOBALS['comment'] = $comment; ?>
<li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
<div id="comment-<?php comment_ID(); ?>">
<div class="comment-author vcard">
<?php printf(__('%s <span class="says">:</span>'), get_comment_author_link()) ?><br />
<?php if ($comment->comment_approved == '0'): ?>
<em><?php _e('Your comment is awaiting moderation.') ?></em>
<br />
<?php endif; ?>
</div>
<div class="comment-meta commentmetadata"><a href="<?php echo esc_url( get_comment_link( $comment->comment_ID ) ) ?>">
<?php printf(__('%1$s, %2$s'), get_comment_date(), get_comment_time()) ?></a><?php edit_comment_link(__('(Edit)'),' ','') ?></div>
<?php comment_text() ?>
```
Here is an example how comments are shown right now: <http://goo.gl/QkSzrd>
I believe, I have to build in get\_avatar somewhere in the line before "get\_author\_link", but everything I did just lead to failure. Either it was just showing the "missing person" avatar (and not the ones connected to those commenting users) or it was deleting the author's name and showing nothing. :\
UPDATE:
Changing the line
```
<?php printf(__('%s <span class="says">:</span>'), get_comment_author_link()) ?><br />
```
to
```
<?php printf(__('%s <span class="says">:</span>'), get_avatar ($comment, '72')) ?><br />
```
brings up the avatar icon, I think, but it deletes the author/username of the comment and it places the avatar some place, I cannot understand (right side corner).
I can live with the right side corner, maybe it is just a CSS issue, **but how do I get author/username of the comment back before the colon?** In other words: I would like to have both, get\_comment\_author\_link **and** the avatar.
|
You're looking for the `get_avatar` function, [documented here](https://codex.wordpress.org/Function_Reference/get_avatar)
```
get_avatar( $id_or_email, $size, $default, $alt )
```
You'll need either a user ID, or an email to use it, something like this should do the trick:
```
echo get_avatar( get_comment_author_email(), 'thumbnail' );
```
If avatars are turned off in settings, this function will not return anything
|
194,861 |
<p>I'm trying to fix an error with pagination of WP page Navi plugin. After I've added posts_per_page parameter to the query I'm getting 404 error when clicking on link page3,4 etc (there are 10 records totally) and after page 8 (where there around 60 records totally). Without this parameter it works fine but I want to display various number of posts under categories. </p>
<p>Here is the code of one of the pages I'm trying to fix:</p>
<pre><code>$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts($query_string .'&posts_per_page=5&paged=' . $paged);
?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<li><a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
<?php else : ?>
<?php _e('Sorry, no posts matched your criteria.'); ?>
<?php endif; ?>
</ul>
<?php if (function_exists('wp_pagenavi')){ wp_pagenavi(); } ?>
</code></pre>
<p>Any help is much appreciated. </p>
|
[
{
"answer_id": 194862,
"author": "EHerman",
"author_id": 43000,
"author_profile": "https://wordpress.stackexchange.com/users/43000",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to take a look at this related issue:\n<a href=\"https://wordpress.stackexchange.com/questions/31524/wp-pagenavi-gives-me-a-404-when-using-wp-query\">WP-PageNavi gives me a 404 when using WP Query</a></p>\n\n<p>Some users mentioning that the page name cannot be the same as the post type you are querying, and others that it may be a conflict with another plugin you are running.</p>\n"
},
{
"answer_id": 194961,
"author": "Dmitry Dorofeev",
"author_id": 76363,
"author_profile": "https://wordpress.stackexchange.com/users/76363",
"pm_score": 1,
"selected": false,
"text": "<p>Finally, I've found an answer. Not sure if it's specific in my case or it's a general WP issue but default value for posts per page set up in WP admin (General > Reading > Maximum number of posts per page) should be less than value for posts_per_page parameter for custom query. In my case, I've changed in WP options value to 3 and for other page changed this to 5 and all working fine now!</p>\n"
}
] |
2015/07/17
|
[
"https://wordpress.stackexchange.com/questions/194861",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76363/"
] |
I'm trying to fix an error with pagination of WP page Navi plugin. After I've added posts\_per\_page parameter to the query I'm getting 404 error when clicking on link page3,4 etc (there are 10 records totally) and after page 8 (where there around 60 records totally). Without this parameter it works fine but I want to display various number of posts under categories.
Here is the code of one of the pages I'm trying to fix:
```
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts($query_string .'&posts_per_page=5&paged=' . $paged);
?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<li><a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
<?php else : ?>
<?php _e('Sorry, no posts matched your criteria.'); ?>
<?php endif; ?>
</ul>
<?php if (function_exists('wp_pagenavi')){ wp_pagenavi(); } ?>
```
Any help is much appreciated.
|
Finally, I've found an answer. Not sure if it's specific in my case or it's a general WP issue but default value for posts per page set up in WP admin (General > Reading > Maximum number of posts per page) should be less than value for posts\_per\_page parameter for custom query. In my case, I've changed in WP options value to 3 and for other page changed this to 5 and all working fine now!
|
194,868 |
<p>In functions.php is it possible to dynamically set the static home page?</p>
<p>The condition could be anything, but for example by domain:</p>
<pre><code>if ( $_SERVER['HTTP_HOST'] == 'domain-one.com' )
set_front_page_slug('domain-one-home');
else if ( $_SERVER['HTTP_HOST'] == 'domain-two.com' )
set_front_page_slug('domain-two-home');
</code></pre>
<p>Note that it should not permanently change the home page set in the WordPress Settings, only for the current page load. I want different visitors to see different homepages.</p>
<p>Any approach welcome that can neatly override the default home page.</p>
|
[
{
"answer_id": 194884,
"author": "Harman Preet",
"author_id": 56650,
"author_profile": "https://wordpress.stackexchange.com/users/56650",
"pm_score": 0,
"selected": false,
"text": "<p>It's better that you should contact the plugin author for the problem you are facing. There is another approach you can follow. Go to the theme directory and in your <code>functions.php</code> file , Paste this little code.</p>\n\n<pre><code>function custom_analytics_code(){\n\n $analytics_code = \"<script>\n (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\n (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\n m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n })(window,document,'script','//www.google-analytics.com/analytics.js','ga');\n\n ga('create', 'UA-XXXXXXXX', 'auto');\n ga('send', 'pageview');\n\n </script>\";\n echo $analytics_code;\n}\nadd_filter('wp_footer','custom_analytics_code' );\n</code></pre>\n\n<p>Add this function in your file i.e. Functions.php file and Replace the <code>$analytic_code</code> variable with your tracking code and save the file and you are done. Now you can use inspect element and search for the code that you have entered so that you can be sure that the code is actually output in the Footer.</p>\n\n<p>Note: You mush have <code>wp_footer();</code>function added to your footer.php file.</p>\n"
},
{
"answer_id": 194885,
"author": "Markovian8261",
"author_id": 76345,
"author_profile": "https://wordpress.stackexchange.com/users/76345",
"pm_score": 1,
"selected": false,
"text": "<p>After reading more about the google analytic site, I found that it can take a while for analytics to start working. After waiting a full night, analytics is now working perfectly.</p>\n"
}
] |
2015/07/18
|
[
"https://wordpress.stackexchange.com/questions/194868",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71270/"
] |
In functions.php is it possible to dynamically set the static home page?
The condition could be anything, but for example by domain:
```
if ( $_SERVER['HTTP_HOST'] == 'domain-one.com' )
set_front_page_slug('domain-one-home');
else if ( $_SERVER['HTTP_HOST'] == 'domain-two.com' )
set_front_page_slug('domain-two-home');
```
Note that it should not permanently change the home page set in the WordPress Settings, only for the current page load. I want different visitors to see different homepages.
Any approach welcome that can neatly override the default home page.
|
After reading more about the google analytic site, I found that it can take a while for analytics to start working. After waiting a full night, analytics is now working perfectly.
|
194,878 |
<p>I am already logged in (with role administrator). If I try to login again with wp-login.php the form just shakes - the error message above the form remains empty. Following a suggestion on this forum I added the following code to my theme's function.php - it works:
/* Create error message for new login attempt if user is already logged in */</p>
<pre><code>add_filter('login_errors','login_error_message');
function login_error_message($error){
//create error message for already logged in
$error = "You are already logged in";
return $error;
}
</code></pre>
|
[
{
"answer_id": 194890,
"author": "Ihor Vorotnov",
"author_id": 47359,
"author_profile": "https://wordpress.stackexchange.com/users/47359",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of working around the error message I would suggest checking if user is already logged in on wp-login.php load. If user is logged in - redirect him/her to wp-admin. You can even add another check and, for example, redirect only administrators to wp-admin, redirect subscribers to site homepage etc.</p>\n\n<pre><code>add_action( 'login_head', 'wpse_redirect_login', 1 );\nfunction wpse_redirect_login() {\n if( is_user_logged_in() ) {\n wp_redirect( admin_url() );\n }\n}\n</code></pre>\n\n<p>Honestly, that's one of the issues I keep wondering why it isn't in Core.</p>\n"
},
{
"answer_id": 199021,
"author": "Matt van Andel",
"author_id": 15324,
"author_profile": "https://wordpress.stackexchange.com/users/15324",
"pm_score": -1,
"selected": false,
"text": "<p>You can detect whether the current user is logged in and redirect them to their profile page with the following…</p>\n\n<pre><code>add_action('wp_loaded','wp_login_redirect_logged_in_user',0);\npublic static function wp_login_redirect_logged_in_user(){\n global $pagenow;\n if ( in_array($pagenow, array('wp-login.php', 'wp-register.php') ) ) {\n if( is_user_logged_in() ) {\n $profile_page = get_edit_user_link( get_current_user_id() );\n wp_safe_redirect( $profile_page );\n die();\n }\n }\n}\n</code></pre>\n"
}
] |
2015/07/18
|
[
"https://wordpress.stackexchange.com/questions/194878",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76375/"
] |
I am already logged in (with role administrator). If I try to login again with wp-login.php the form just shakes - the error message above the form remains empty. Following a suggestion on this forum I added the following code to my theme's function.php - it works:
/\* Create error message for new login attempt if user is already logged in \*/
```
add_filter('login_errors','login_error_message');
function login_error_message($error){
//create error message for already logged in
$error = "You are already logged in";
return $error;
}
```
|
Instead of working around the error message I would suggest checking if user is already logged in on wp-login.php load. If user is logged in - redirect him/her to wp-admin. You can even add another check and, for example, redirect only administrators to wp-admin, redirect subscribers to site homepage etc.
```
add_action( 'login_head', 'wpse_redirect_login', 1 );
function wpse_redirect_login() {
if( is_user_logged_in() ) {
wp_redirect( admin_url() );
}
}
```
Honestly, that's one of the issues I keep wondering why it isn't in Core.
|
194,896 |
<p>How can I add the following HTML code into one of my web pages? It's a web form that relies on css and a few java script.</p>
<p>Below is the raw HTML code.</p>
<pre><code><head>
<link href="css/style.css" rel="stylesheet">
<script src="js/jquery.min.js"></script>
<script src="js/slider.js"></script>
<script src="js/rslider.js"></script>
<script src="js/popup.js"></script>
</head>
<body>
<div class="wrapper">
<form id="signup_form" method="post" name="signup_form" action="post">
<input type="hidden" name="token" value="2f8247702b1f51b36dad1d8f4ba66211de0c31af">
<input type="hidden" name="configure" value="true">
......
</body>
</code></pre>
<p>I've added the following with Visual Composer but that causes it to stop working (just for that page).</p>
<pre><code><link href="css/style.css" rel="stylesheet">
<script src="js/jquery.min.js"></script>
<script src="js/slider.js"></script>
<script src="js/rslider.js"></script>
<script src="js/popup.js"></script>
<div class="wrapper">
<form id="signup_form" method="post" name="signup_form" action="post">
<input type="hidden" name="token" value="2f8247702b1f51b36dad1d8f4ba66211de0c31af">
<input type="hidden" name="configure" value="true">
......
</code></pre>
<p>I'm guessing this isn't the cleanest way. What would be better?</p>
|
[
{
"answer_id": 194902,
"author": "David in Mississippi",
"author_id": 76383,
"author_profile": "https://wordpress.stackexchange.com/users/76383",
"pm_score": 0,
"selected": false,
"text": "<p>Toodarday,</p>\n\n<p>For the code you want to put in your <head> section, you should do this in the header.php file.</p>\n\n<p>To do this, go to your WordPress dashboard, hover your cursor over APPEARANCE in the left-side menu bar, and click on EDITOR. </p>\n\n<p>When the editor screen appears, in the right column, you should see the listing \"Header\" with (header.php) below it. Click on that listing to edit your header.php file.</p>\n\n<p>Copy the code you want to put in your tag, and paste it in between the <head> and the </head> tags, then scroll down and click the [Update File] button. </p>\n\n<p>This will put your code in the proper place. </p>\n\n<p>Be aware, this will put the code into the header tag for ALL your pages.</p>\n\n<p>If you want to put the code in place for just one page, then you should use CONDITIONAL tags in PHP. You can find out about conditional tags in <a href=\"http://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow\"> the WordPress Conditional Tags Codex</a>.</p>\n\n<p>but in a nutshell, if for example you want this code only to appear on your home page, then you would put the following PHP code into your header.php file:</p>\n\n<pre><code><?php\n if (is_home())\n{?>\nYour Javascript Goes Here\n<?php } ?>\n</code></pre>\n\n<p>If it is not your home page, you would replace the IF statement above with one appropriate to the page to which you want to limit the code appearing.</p>\n\n<p>As for the form in the <body> section, you can simply add this code in the text view section of your page/post editor - I THINK this is true, but I haven't tested it.</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 194914,
"author": "Mahavar Hitesh",
"author_id": 75414,
"author_profile": "https://wordpress.stackexchange.com/users/75414",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>You want to add <strong>CSS OR SCRIPT</strong> in wordpress theme .. so.</p>\n</blockquote>\n\n<p>wordpress provide a <strong>functions.php</strong> in copy and past YOUR <strong>CSS LINK OR JS SCRIPT LINK</strong>.</p>\n\n<pre><code>/**\n * Enqueue scripts and styles.\n */\nfunction function_name() { \n\n // ADD STYLE\n wp_enqueue_style( 'CSS-ID', get_template_directory_uri() .'/css/style.css','', '3.3.1' ); \n\n // ADD SCRIPT\n wp_enqueue_script( 'JS-ID', get_template_directory_uri() . '/js/SCRIPT.js', array(), null, true ); \n\n}\nadd_action( 'wp_enqueue_scripts', 'function_name' );\n</code></pre>\n\n<p><a href=\"/questions/tagged/wordpress\" class=\"post-tag\" title=\"show questions tagged 'wordpress'\" rel=\"tag\">wordpress</a></p>\n"
},
{
"answer_id": 194975,
"author": "David in Mississippi",
"author_id": 76383,
"author_profile": "https://wordpress.stackexchange.com/users/76383",
"pm_score": 0,
"selected": false,
"text": "<p>To load the css/js on just one page, please see my earlier answer, and use a WordPress Conditional Tag, just as I showed you in the code example, except replace \"Home\" in the example with the conditional tag for the page you want this code on. </p>\n\n<p>You can find the conditional tag for any specific page by looking it up as indicated in the CODEX link in my earlier answer.</p>\n"
},
{
"answer_id": 289972,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 1,
"selected": false,
"text": "<p>Add CSS and JS Particular Page. Put this code in your current active theme function.php file </p>\n\n<pre><code><?php\n function function_name() {\n is_page( 'about-me' ) //is_page( 'PAGE_SLUG_NAME' )\n {\n wp_enqueue_style( 'stylecss', get_template_directory_uri() .'/css/style.css','', '3.3.1' ); \n wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ));\n } \n }\n add_action( 'wp_enqueue_scripts', 'function_name' );\n ?>\n</code></pre>\n"
}
] |
2015/07/18
|
[
"https://wordpress.stackexchange.com/questions/194896",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76382/"
] |
How can I add the following HTML code into one of my web pages? It's a web form that relies on css and a few java script.
Below is the raw HTML code.
```
<head>
<link href="css/style.css" rel="stylesheet">
<script src="js/jquery.min.js"></script>
<script src="js/slider.js"></script>
<script src="js/rslider.js"></script>
<script src="js/popup.js"></script>
</head>
<body>
<div class="wrapper">
<form id="signup_form" method="post" name="signup_form" action="post">
<input type="hidden" name="token" value="2f8247702b1f51b36dad1d8f4ba66211de0c31af">
<input type="hidden" name="configure" value="true">
......
</body>
```
I've added the following with Visual Composer but that causes it to stop working (just for that page).
```
<link href="css/style.css" rel="stylesheet">
<script src="js/jquery.min.js"></script>
<script src="js/slider.js"></script>
<script src="js/rslider.js"></script>
<script src="js/popup.js"></script>
<div class="wrapper">
<form id="signup_form" method="post" name="signup_form" action="post">
<input type="hidden" name="token" value="2f8247702b1f51b36dad1d8f4ba66211de0c31af">
<input type="hidden" name="configure" value="true">
......
```
I'm guessing this isn't the cleanest way. What would be better?
|
Add CSS and JS Particular Page. Put this code in your current active theme function.php file
```
<?php
function function_name() {
is_page( 'about-me' ) //is_page( 'PAGE_SLUG_NAME' )
{
wp_enqueue_style( 'stylecss', get_template_directory_uri() .'/css/style.css','', '3.3.1' );
wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ));
}
}
add_action( 'wp_enqueue_scripts', 'function_name' );
?>
```
|
194,898 |
<p>I would like to display the other paths/pages which are before the current site, plus the current site as you can see here.</p>
<blockquote>
<p><a href="https://i.stack.imgur.com/rLOco.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rLOco.png" alt="screenshot"></a></p>
</blockquote>
<p>I searched the web and I couldn't found something. It may also be that I do not know what I should look for.</p>
|
[
{
"answer_id": 194902,
"author": "David in Mississippi",
"author_id": 76383,
"author_profile": "https://wordpress.stackexchange.com/users/76383",
"pm_score": 0,
"selected": false,
"text": "<p>Toodarday,</p>\n\n<p>For the code you want to put in your <head> section, you should do this in the header.php file.</p>\n\n<p>To do this, go to your WordPress dashboard, hover your cursor over APPEARANCE in the left-side menu bar, and click on EDITOR. </p>\n\n<p>When the editor screen appears, in the right column, you should see the listing \"Header\" with (header.php) below it. Click on that listing to edit your header.php file.</p>\n\n<p>Copy the code you want to put in your tag, and paste it in between the <head> and the </head> tags, then scroll down and click the [Update File] button. </p>\n\n<p>This will put your code in the proper place. </p>\n\n<p>Be aware, this will put the code into the header tag for ALL your pages.</p>\n\n<p>If you want to put the code in place for just one page, then you should use CONDITIONAL tags in PHP. You can find out about conditional tags in <a href=\"http://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow\"> the WordPress Conditional Tags Codex</a>.</p>\n\n<p>but in a nutshell, if for example you want this code only to appear on your home page, then you would put the following PHP code into your header.php file:</p>\n\n<pre><code><?php\n if (is_home())\n{?>\nYour Javascript Goes Here\n<?php } ?>\n</code></pre>\n\n<p>If it is not your home page, you would replace the IF statement above with one appropriate to the page to which you want to limit the code appearing.</p>\n\n<p>As for the form in the <body> section, you can simply add this code in the text view section of your page/post editor - I THINK this is true, but I haven't tested it.</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 194914,
"author": "Mahavar Hitesh",
"author_id": 75414,
"author_profile": "https://wordpress.stackexchange.com/users/75414",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>You want to add <strong>CSS OR SCRIPT</strong> in wordpress theme .. so.</p>\n</blockquote>\n\n<p>wordpress provide a <strong>functions.php</strong> in copy and past YOUR <strong>CSS LINK OR JS SCRIPT LINK</strong>.</p>\n\n<pre><code>/**\n * Enqueue scripts and styles.\n */\nfunction function_name() { \n\n // ADD STYLE\n wp_enqueue_style( 'CSS-ID', get_template_directory_uri() .'/css/style.css','', '3.3.1' ); \n\n // ADD SCRIPT\n wp_enqueue_script( 'JS-ID', get_template_directory_uri() . '/js/SCRIPT.js', array(), null, true ); \n\n}\nadd_action( 'wp_enqueue_scripts', 'function_name' );\n</code></pre>\n\n<p><a href=\"/questions/tagged/wordpress\" class=\"post-tag\" title=\"show questions tagged 'wordpress'\" rel=\"tag\">wordpress</a></p>\n"
},
{
"answer_id": 194975,
"author": "David in Mississippi",
"author_id": 76383,
"author_profile": "https://wordpress.stackexchange.com/users/76383",
"pm_score": 0,
"selected": false,
"text": "<p>To load the css/js on just one page, please see my earlier answer, and use a WordPress Conditional Tag, just as I showed you in the code example, except replace \"Home\" in the example with the conditional tag for the page you want this code on. </p>\n\n<p>You can find the conditional tag for any specific page by looking it up as indicated in the CODEX link in my earlier answer.</p>\n"
},
{
"answer_id": 289972,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 1,
"selected": false,
"text": "<p>Add CSS and JS Particular Page. Put this code in your current active theme function.php file </p>\n\n<pre><code><?php\n function function_name() {\n is_page( 'about-me' ) //is_page( 'PAGE_SLUG_NAME' )\n {\n wp_enqueue_style( 'stylecss', get_template_directory_uri() .'/css/style.css','', '3.3.1' ); \n wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ));\n } \n }\n add_action( 'wp_enqueue_scripts', 'function_name' );\n ?>\n</code></pre>\n"
}
] |
2015/07/18
|
[
"https://wordpress.stackexchange.com/questions/194898",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
I would like to display the other paths/pages which are before the current site, plus the current site as you can see here.
>
> [](https://i.stack.imgur.com/rLOco.png)
>
>
>
I searched the web and I couldn't found something. It may also be that I do not know what I should look for.
|
Add CSS and JS Particular Page. Put this code in your current active theme function.php file
```
<?php
function function_name() {
is_page( 'about-me' ) //is_page( 'PAGE_SLUG_NAME' )
{
wp_enqueue_style( 'stylecss', get_template_directory_uri() .'/css/style.css','', '3.3.1' );
wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ));
}
}
add_action( 'wp_enqueue_scripts', 'function_name' );
?>
```
|
194,906 |
<p>I need help to finish this last bit of php code. I'm trying to create an admin options page similar to in admin>settings>discussions like how a user can select an avatar, but instead of selecting an avatar, the user selects a style option that makes a change to the theme (by enqueueing a CSS file on the frontend).</p>
<p>My CSS files are complete. For the php, so far I have this:</p>
<pre><code><?php
// register CSS files ready
function register_custom_styles() {
wp_register_style( 'style1', plugins_url( '/css/style1.css', (__FILE__) ) );
wp_register_style( 'style2', plugins_url( '/css/style2.css', (__FILE__) ) );
wp_register_style( 'style3', plugins_url( '/css/style3.css', (__FILE__) ) );
}
add_action( 'init', 'register_custom_styles' );
//create admin sub menu - admin>appearance>styles
add_action('admin_menu', 'my_custom_submenu');
function my_custom_submenu() {
add_submenu_page( 'themes.php', 'Styles', 'Styles', 'manage_options', 'styles', 'my_custom_submenu_page' );
}
//create admin page for admin>appearance>styles
function my_custom_submenu_page() {
?>
<div>
<h2>Select Style</h2>
<form method="post" action="options.php">
<!--this option to wp_enqueue_style('style1')-->
<label> <input type="radio" name="myoption[radio1]" value="style1" /> <img src="//path-to-style1-img" /> Style1 </label>
<br />
<!--this option to wp_enqueue_style('style2')-->
<label> <input type="radio" name="myoption[radio1]" value="style2" /> <img src="//path-to-style2-img" /> Style2 </label>
<br />
<!--this option to wp_enqueue_style('style3')-->
<label> <input type="radio" name="myoption[radio1]" value="style3" /> <img src="path-to-style3-img" /> Style3 </label>
<br />
<?php submit_button(); ?>
</form>
</div>
<?php
}
</code></pre>
<p>As you can see, when a user selects a radio input and clicks the submit button, I don't know how to connect the option with the registered CSS file.</p>
<p><a href="https://codex.wordpress.org/Creating_Options_Pages" rel="nofollow">https://codex.wordpress.org/Creating_Options_Pages</a> shows how to create an options page, but there are no examples of how to enqueue a CSS file for an option.</p>
<p>Any help appreciated.</p>
|
[
{
"answer_id": 194912,
"author": "Mahavar Hitesh",
"author_id": 75414,
"author_profile": "https://wordpress.stackexchange.com/users/75414",
"pm_score": 0,
"selected": false,
"text": "<p>Hay In wordpress theme you can add option panel you can not registre script or wp_enqueue_scripts you can add </p>\n\n<pre><code>/*-----------------------------------------------------------*\n/* THEME OPTION ADMIN PRINT SCRIPT EXAMPLE\n/*-----------------------------------------------------------*/\n\nadd_action( 'admin_menu', 'ease_print_script' );\nfunction ease_print_script() { \n add_action( 'admin_print_scripts-' . $ease_options_page, 'ease_print_scripts' );\n}\nfunction ease_print_scripts() {\n wp_enqueue_style( 'bootstrap', get_template_directory_uri().'/framework/css/bootstrap.css'); \n wp_enqueue_style( 'bootstrap.vertical-tabs', get_template_directory_uri().'/framework/css/bootstrap.vertical-tabs.css');\n wp_enqueue_script( 'script', get_template_directory_uri().'/framework/js/script.js');\n wp_enqueue_script( 'bootstrap', get_template_directory_uri().'/framework/js/bootstrap.js'); \n} \n</code></pre>\n\n<blockquote>\n <p>YOUR OPTION PANEL PAGE CREATED CODE HERE..</p>\n</blockquote>\n\n<pre><code>/*-----------------------------------------------------------*\n/* THEME OPTION PAGE\n/*-----------------------------------------------------------*/\nadd_action( 'admin_init', 'ease_add_options_1' );\nfunction ease_add_options_1() {\n // Register new options\n register_setting( 'ease_options', 'ease_options', 'ease_options_validate' );\n}\n/*-----------------------------------------------------------*\n/* THEME OPTION ADMIN IN MENU\n/*-----------------------------------------------------------*/\nadd_action( 'admin_menu', 'ease_add_page_1' );\nfunction ease_add_page_1() {\n /**\n * IF you want to add in wordpress == menu page OR add theme page ==\n */\n\n // add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position );\n // MENU PAGE\n $ease_options_page = add_menu_page( '__ease', 'Theme Option', 'manage_options', '__ease', 'yout_code_here' );\n\n // THEME PAGE\n // add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position );\n // $ease_options_page = add_theme_page( 'ease', 'Theme Option', 'manage_options', 'ease', 'ease_options_page' );\n\n}\nfunction yout_code_here(){\n ?>\n <h2>Select Style</h2>\n <form method=\"post\" action=\"options.php\">\n <!--this option to wp_enqueue_style('style1')-->\n <label>\n <input type=\"radio\" name=\"myoption[radio1]\" value=\"style1\" />\n <img src=\"//path-to-style1-img\" /> Style1 </label>\n <br />\n <!--this option to wp_enqueue_style('style2')-->\n <label>\n <input type=\"radio\" name=\"myoption[radio1]\" value=\"style2\" />\n <img src=\"//path-to-style2-img\" /> Style2 </label>\n <br />\n <!--this option to wp_enqueue_style('style3')-->\n <label>\n <input type=\"radio\" name=\"myoption[radio1]\" value=\"style3\" />\n <img src=\"path-to-style3-img\" /> Style3 </label>\n <br />\n <?php submit_button(); ?>\n </form>\n <?php \n}\n</code></pre>\n\n<p><a href=\"/questions/tagged/wordpress\" class=\"post-tag\" title=\"show questions tagged 'wordpress'\" rel=\"tag\">wordpress</a><a href=\"/questions/tagged/option-panel\" class=\"post-tag\" title=\"show questions tagged 'option-panel'\" rel=\"tag\">option-panel</a></p>\n"
},
{
"answer_id": 195200,
"author": "user3438958",
"author_id": 50534,
"author_profile": "https://wordpress.stackexchange.com/users/50534",
"pm_score": 3,
"selected": true,
"text": "<p>I finally got it to work after a long time of trying to figure this out!</p>\n\n<p>Credit to Samuel Elh for helping me, <a href=\"http://sam.elegance-style.com/\" rel=\"nofollow\">http://sam.elegance-style.com/</a></p>\n\n<p>This is useful if anyone wants to allow users to make small style changes to a theme. Rather than create many child themes, if you just need some stylesheet overrules to make changes to a theme, this is ideal:</p>\n\n<pre><code> /*\nPlugin Name: test1\n*/\n\n// register CSS files ready\nfunction register_custom_styles() {\n wp_register_style( 'style1', plugins_url( '/css/themes/s1.css', (__FILE__) ) );\n wp_register_style( 'style2', plugins_url( '/css/themes/s2.css', (__FILE__) ) );\n wp_register_style( 'style3', plugins_url( '/css/themes/s3.css', (__FILE__) ) );\n}\nadd_action( 'init', 'register_custom_styles' );\n\n//create admin sub menu - admin>appearance>styles\nadd_action('admin_menu', 'my_custom_submenu');\nfunction my_custom_submenu() {\n add_submenu_page( 'themes.php', 'Styles', 'Styles', 'manage_options', 'styles', 'my_custom_submenu_page' );\n}\n\n// register option\nadd_action( 'admin_init', 'elh_register_settings' );\nfunction elh_register_settings() {\n register_setting( 'elh-settings-group', 'user_select_styles' );\n}\n\n//create admin page for admin>appearance>styles\nfunction my_custom_submenu_page() {\n?>\n<div>\n <h2>Select Style</h2>\n <form method=\"post\" enctype=\"multipart/form-data\" action=\"options.php\">\n <?php\n settings_fields( 'elh-settings-group' );\n do_settings_sections( 'elh-settings-group' );\n $selected = (get_option('user_select_styles') != '') ? get_option('user_select_styles') : '';\n ?>\n\n <!--this option to wp_enqueue_style('style1')-->\n <label> <input type=\"radio\" name=\"user_select_styles\" value=\"style1\" <?php if($selected == \"style1\") echo \"checked\"; ?> /> <!--<img src=\"//path-to-style1-img\" /> --> Style1 </label> \n\n <br /> \n\n <!--this option to wp_enqueue_style('style2')-->\n <label> <input type=\"radio\" name=\"user_select_styles\" value=\"style2\" <?php if($selected == \"style2\") echo \"checked\"; ?> /> <!--<img src=\"//path-to-style2-img\" /> --> Style2 </label> \n\n <br /> \n\n <!--this option to wp_enqueue_style('style3')-->\n <label> <input type=\"radio\" name=\"user_select_styles\" value=\"style3\" <?php if($selected == \"style3\") echo \"checked\"; ?> /> <!--<img src=\"path-to-style3-img\" /> --> Style3 </label> \n\n <br /> \n\n <?php submit_button(); ?>\n\n </form>\n\n <h2><?php if($selected != '') printf(\"You have selected %s.\", $selected); ?></h2>\n\n</div>\n<?php\n}\n\nfunction enqueue_my_css() {\n\n $selected = (get_option('user_select_styles') != '') ? get_option('user_select_styles') : '';\n if($selected != '')\n wp_enqueue_style( $selected , plugins_url( '/css/'.$selected.'.css', (__FILE__) ) );\n\n}\nadd_action('wp_enqueue_scripts', 'enqueue_my_css', 99);\n</code></pre>\n\n<p>Not sure if I'm supposed to tick my own answer.</p>\n"
}
] |
2015/07/18
|
[
"https://wordpress.stackexchange.com/questions/194906",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/50534/"
] |
I need help to finish this last bit of php code. I'm trying to create an admin options page similar to in admin>settings>discussions like how a user can select an avatar, but instead of selecting an avatar, the user selects a style option that makes a change to the theme (by enqueueing a CSS file on the frontend).
My CSS files are complete. For the php, so far I have this:
```
<?php
// register CSS files ready
function register_custom_styles() {
wp_register_style( 'style1', plugins_url( '/css/style1.css', (__FILE__) ) );
wp_register_style( 'style2', plugins_url( '/css/style2.css', (__FILE__) ) );
wp_register_style( 'style3', plugins_url( '/css/style3.css', (__FILE__) ) );
}
add_action( 'init', 'register_custom_styles' );
//create admin sub menu - admin>appearance>styles
add_action('admin_menu', 'my_custom_submenu');
function my_custom_submenu() {
add_submenu_page( 'themes.php', 'Styles', 'Styles', 'manage_options', 'styles', 'my_custom_submenu_page' );
}
//create admin page for admin>appearance>styles
function my_custom_submenu_page() {
?>
<div>
<h2>Select Style</h2>
<form method="post" action="options.php">
<!--this option to wp_enqueue_style('style1')-->
<label> <input type="radio" name="myoption[radio1]" value="style1" /> <img src="//path-to-style1-img" /> Style1 </label>
<br />
<!--this option to wp_enqueue_style('style2')-->
<label> <input type="radio" name="myoption[radio1]" value="style2" /> <img src="//path-to-style2-img" /> Style2 </label>
<br />
<!--this option to wp_enqueue_style('style3')-->
<label> <input type="radio" name="myoption[radio1]" value="style3" /> <img src="path-to-style3-img" /> Style3 </label>
<br />
<?php submit_button(); ?>
</form>
</div>
<?php
}
```
As you can see, when a user selects a radio input and clicks the submit button, I don't know how to connect the option with the registered CSS file.
<https://codex.wordpress.org/Creating_Options_Pages> shows how to create an options page, but there are no examples of how to enqueue a CSS file for an option.
Any help appreciated.
|
I finally got it to work after a long time of trying to figure this out!
Credit to Samuel Elh for helping me, <http://sam.elegance-style.com/>
This is useful if anyone wants to allow users to make small style changes to a theme. Rather than create many child themes, if you just need some stylesheet overrules to make changes to a theme, this is ideal:
```
/*
Plugin Name: test1
*/
// register CSS files ready
function register_custom_styles() {
wp_register_style( 'style1', plugins_url( '/css/themes/s1.css', (__FILE__) ) );
wp_register_style( 'style2', plugins_url( '/css/themes/s2.css', (__FILE__) ) );
wp_register_style( 'style3', plugins_url( '/css/themes/s3.css', (__FILE__) ) );
}
add_action( 'init', 'register_custom_styles' );
//create admin sub menu - admin>appearance>styles
add_action('admin_menu', 'my_custom_submenu');
function my_custom_submenu() {
add_submenu_page( 'themes.php', 'Styles', 'Styles', 'manage_options', 'styles', 'my_custom_submenu_page' );
}
// register option
add_action( 'admin_init', 'elh_register_settings' );
function elh_register_settings() {
register_setting( 'elh-settings-group', 'user_select_styles' );
}
//create admin page for admin>appearance>styles
function my_custom_submenu_page() {
?>
<div>
<h2>Select Style</h2>
<form method="post" enctype="multipart/form-data" action="options.php">
<?php
settings_fields( 'elh-settings-group' );
do_settings_sections( 'elh-settings-group' );
$selected = (get_option('user_select_styles') != '') ? get_option('user_select_styles') : '';
?>
<!--this option to wp_enqueue_style('style1')-->
<label> <input type="radio" name="user_select_styles" value="style1" <?php if($selected == "style1") echo "checked"; ?> /> <!--<img src="//path-to-style1-img" /> --> Style1 </label>
<br />
<!--this option to wp_enqueue_style('style2')-->
<label> <input type="radio" name="user_select_styles" value="style2" <?php if($selected == "style2") echo "checked"; ?> /> <!--<img src="//path-to-style2-img" /> --> Style2 </label>
<br />
<!--this option to wp_enqueue_style('style3')-->
<label> <input type="radio" name="user_select_styles" value="style3" <?php if($selected == "style3") echo "checked"; ?> /> <!--<img src="path-to-style3-img" /> --> Style3 </label>
<br />
<?php submit_button(); ?>
</form>
<h2><?php if($selected != '') printf("You have selected %s.", $selected); ?></h2>
</div>
<?php
}
function enqueue_my_css() {
$selected = (get_option('user_select_styles') != '') ? get_option('user_select_styles') : '';
if($selected != '')
wp_enqueue_style( $selected , plugins_url( '/css/'.$selected.'.css', (__FILE__) ) );
}
add_action('wp_enqueue_scripts', 'enqueue_my_css', 99);
```
Not sure if I'm supposed to tick my own answer.
|
194,934 |
<p>Is there an easy method of adding the last few words of the posts, added to the trimmed excerpt that is automatically generated for post displayed on category pages?</p>
<p>Currently it will only show the first given number of words, and I would like it to have the first few words and the last few words, something like following</p>
<blockquote>
<p>1 2 3 4 5 6 [...] 997 998 999 1000</p>
</blockquote>
|
[
{
"answer_id": 194937,
"author": "terminator",
"author_id": 55034,
"author_profile": "https://wordpress.stackexchange.com/users/55034",
"pm_score": 3,
"selected": true,
"text": "<p>You can achieve this by using the_excerpt filter. You can read further on the codex. Just paste this code in functions.php and set the value of $i = no of words from the end you want.</p>\n\n<pre><code>add_filter('the_excerpt','my_excerpt');\nfunction my_excerpt(){\n global $post; \n $excerpt=get_the_excerpt();\n $content = get_the_content(); //gets the whole content\n $content =strip_tags($content) ; //strips html tags \n $content = explode(\" \", $content); //stores each word in an array\n $size = count($content); //counts the length of array \n $last=\"\"; //initialize an empty sting\n $i=4; //no of words from the last you want\n while($i>0){\n $last.= $content[$size-$i]; \n $last.=\" \";\n $i--; \n } \n return $excerpt.\"......\".$last;\n}\n</code></pre>\n\n<p>Now use <code>the_excerpt();</code> to output the kind excerpt you want. \nAll the best and let me know if it worked or not.</p>\n"
},
{
"answer_id": 194944,
"author": "Mahavar Hitesh",
"author_id": 75414,
"author_profile": "https://wordpress.stackexchange.com/users/75414",
"pm_score": 1,
"selected": false,
"text": "<p>You can wordpress excerpt using maximam <strong>character</strong> OR <strong>word</strong> count and display like </p>\n\n<blockquote>\n <p>Loriem ipsum[...]</p>\n</blockquote>\n\n<p>so I have solution.</p>\n\n<p>This code put in <strong>function.php</strong></p>\n\n<pre><code>/** \n * The Excerpt for word counting in the_content or excerpt.\n */ \nfunction getCharCut($text, $limit)\n{\n $char_cut=substr(strip_tags(stripslashes($text)),0,$limit);\n if(strlen($text)<=$limit) \n return $char_cut; \n else\n return esc_html($char_cut.\" [...]\"); \n} \n</code></pre>\n\n<p>You can use the <strong>excerpt</strong> or <strong>content</strong> count character OR word .</p>\n\n<pre><code> <?php\n if(get_the_excerpt())\n {\n $mycontent = get_the_excerpt();\n echo getCharCut($mycontent, 105);\n } \n ?>\n</code></pre>\n"
}
] |
2015/07/19
|
[
"https://wordpress.stackexchange.com/questions/194934",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16198/"
] |
Is there an easy method of adding the last few words of the posts, added to the trimmed excerpt that is automatically generated for post displayed on category pages?
Currently it will only show the first given number of words, and I would like it to have the first few words and the last few words, something like following
>
> 1 2 3 4 5 6 [...] 997 998 999 1000
>
>
>
|
You can achieve this by using the\_excerpt filter. You can read further on the codex. Just paste this code in functions.php and set the value of $i = no of words from the end you want.
```
add_filter('the_excerpt','my_excerpt');
function my_excerpt(){
global $post;
$excerpt=get_the_excerpt();
$content = get_the_content(); //gets the whole content
$content =strip_tags($content) ; //strips html tags
$content = explode(" ", $content); //stores each word in an array
$size = count($content); //counts the length of array
$last=""; //initialize an empty sting
$i=4; //no of words from the last you want
while($i>0){
$last.= $content[$size-$i];
$last.=" ";
$i--;
}
return $excerpt."......".$last;
}
```
Now use `the_excerpt();` to output the kind excerpt you want.
All the best and let me know if it worked or not.
|
194,965 |
<p>I am using the Plugin Visual Composer with in a new Theme I develop. My question is about mapping shortcodes to Visual Composer arrays.</p>
<p>The problem I get, when I try to make a custom element for an image. So here is what I did:</p>
<p>I created an php file <code>vc_shortcodes.php</code> for my arrays of params. The matching shortcodes are in <code>functions.php</code>.</p>
<p>For the array type <code>textarea_html</code> everything works fine and I can see me text as supposed at the front end.</p>
<p>Now I am trying to us an array with type <code>attach_image</code>. It is the following:</p>
<pre><code>/Bild
add_action( 'vc_before_init', 'webnuts_bild' );
function webnuts_bild() {
vc_map( array(
"name" => __( "Bild", "my-text-domain" ),
"base" => "image_url",
"icon" => "icon-webnuts",
'admin_enqueue_css' => array('/wp-content/themes/devdmbootstrap3-child/framework/css/admin-wn.css' ),
"class" => "wn-bild",
"category" => __( "Content", "my-text-domain"),
"params" => array(
array(
"type" => "attach_image",
"holder" => "img",
"class" => "",
"heading" => __( "Hintergrundbild", "my-text-domain" ),
"param_name" => "image_url",
"value" => __( "", "my-text-domain" ),
"description" => __( "Bitte wähle hier ein Bild aus oder lade eins hoch", "my-text-domain" )
)
)
) );
}
</code></pre>
<p>It works so far, that I can chose the element in the backend an attach an image to it. But I guess I make something wrong in the functions.php</p>
<p>I am sure I make something wrong in <code>functions.php</code>... There I use the following:</p>
<pre><code>add_shortcode( 'image_url', 'bild_func' );
function bild_func( $atts ) {
extract( shortcode_atts( array(
'image_url' => 'Bild wird nicht richtig angezeigt'
), $atts ) );
return "<div class='bild-wrapper'><img src='" . "{$image_url}" . "'/></div>";
}
</code></pre>
<p>This is what gets returned in the browser:</p>
<pre><code><div class="bild-wrapper">
<img src="9">
</div>
</code></pre>
<p>What do I have to change so the image gets shown in the browser?</p>
|
[
{
"answer_id": 203601,
"author": "Raffael Lima",
"author_id": 80907,
"author_profile": "https://wordpress.stackexchange.com/users/80907",
"pm_score": 2,
"selected": false,
"text": "<p>Visual Composer adds the image ID to the generated shortcode. This gives you more flexibility with image sizes. You can use it like this:</p>\n\n<pre><code>$imageSrc = wp_get_attachment_image_src($image_url, 'thumbnail');\nif( $imageSrc ) {\n echo '<img src=\"' . $imageSrc[0] . '\" />';\n}\n</code></pre>\n\n<p>The <code>thumbnail</code> param could be replaced by <code>medium</code> or another valid image size. The <code>if</code> clause is there to verify that the image is really there (not deleted).</p>\n\n<p>Advice: Rename the <code>param_name</code> to <code>image_id</code> so you won't get confused when using the code later.</p>\n\n<p>Source: <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/</a></p>\n"
},
{
"answer_id": 241122,
"author": "mlimon",
"author_id": 64458,
"author_profile": "https://wordpress.stackexchange.com/users/64458",
"pm_score": 0,
"selected": false,
"text": "<p>Use you image url by your attachment id that already shown. So just use <code>wp_get_attachment_image_src</code> to get the attachment url. like:</p>\n\n<pre><code>add_shortcode( 'image_url', 'bild_func' );\nfunction bild_func( $atts ) {\n extract( shortcode_atts( array(\n 'image_url' => ''\n ), $atts ) );\n\n /* Let's get the URL from that image */\n if(isset($a['image_url'])) {\n $image_url = wp_get_attachment_image_src( $a['image_url'], 'full' );;\n } else {\n $image_url = ''; // default image or something if you want.\n }\n\n return \"<div class='bild-wrapper'><img src='\" . \"{$image_url[0]}\" . \"'/></div>\";\n}\n</code></pre>\n\n<p>Hope it make sense !</p>\n"
},
{
"answer_id": 249102,
"author": "Philipp Schreiber",
"author_id": 21406,
"author_profile": "https://wordpress.stackexchange.com/users/21406",
"pm_score": 0,
"selected": false,
"text": "<p>Visual Composer does the right thing with providing the image id because you can the get the image in the best size for your needs. You could do it like that:</p>\n\n<pre><code>// Replace 'thumbnail' with any valid wordpress image size.\n$imageSrc = wp_get_attachment_image_src($image_url, 'thumbnail'); \n// Check if the image is still there\nif( $imageSrc ) {\n echo '<img src=\"' . $imageSrc[0] . '\" />';\n}\n</code></pre>\n\n<p>You could also rename the 'param_name' in 'vc_map' to 'image_id' so you understand the code later.</p>\n"
}
] |
2015/07/19
|
[
"https://wordpress.stackexchange.com/questions/194965",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76425/"
] |
I am using the Plugin Visual Composer with in a new Theme I develop. My question is about mapping shortcodes to Visual Composer arrays.
The problem I get, when I try to make a custom element for an image. So here is what I did:
I created an php file `vc_shortcodes.php` for my arrays of params. The matching shortcodes are in `functions.php`.
For the array type `textarea_html` everything works fine and I can see me text as supposed at the front end.
Now I am trying to us an array with type `attach_image`. It is the following:
```
/Bild
add_action( 'vc_before_init', 'webnuts_bild' );
function webnuts_bild() {
vc_map( array(
"name" => __( "Bild", "my-text-domain" ),
"base" => "image_url",
"icon" => "icon-webnuts",
'admin_enqueue_css' => array('/wp-content/themes/devdmbootstrap3-child/framework/css/admin-wn.css' ),
"class" => "wn-bild",
"category" => __( "Content", "my-text-domain"),
"params" => array(
array(
"type" => "attach_image",
"holder" => "img",
"class" => "",
"heading" => __( "Hintergrundbild", "my-text-domain" ),
"param_name" => "image_url",
"value" => __( "", "my-text-domain" ),
"description" => __( "Bitte wähle hier ein Bild aus oder lade eins hoch", "my-text-domain" )
)
)
) );
}
```
It works so far, that I can chose the element in the backend an attach an image to it. But I guess I make something wrong in the functions.php
I am sure I make something wrong in `functions.php`... There I use the following:
```
add_shortcode( 'image_url', 'bild_func' );
function bild_func( $atts ) {
extract( shortcode_atts( array(
'image_url' => 'Bild wird nicht richtig angezeigt'
), $atts ) );
return "<div class='bild-wrapper'><img src='" . "{$image_url}" . "'/></div>";
}
```
This is what gets returned in the browser:
```
<div class="bild-wrapper">
<img src="9">
</div>
```
What do I have to change so the image gets shown in the browser?
|
Visual Composer adds the image ID to the generated shortcode. This gives you more flexibility with image sizes. You can use it like this:
```
$imageSrc = wp_get_attachment_image_src($image_url, 'thumbnail');
if( $imageSrc ) {
echo '<img src="' . $imageSrc[0] . '" />';
}
```
The `thumbnail` param could be replaced by `medium` or another valid image size. The `if` clause is there to verify that the image is really there (not deleted).
Advice: Rename the `param_name` to `image_id` so you won't get confused when using the code later.
Source: <https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/>
|
194,983 |
<p>I need to add a custom parameter/segment to the post URL. </p>
<p>For example, when I have a post at <code>example.com/post-name</code>, I need to add another segment like <code>example.com/post-name/places</code>. After that, I need to add a dynamic segment like <code>example.com/post-name/places/dynamic-value</code>.</p>
<p>I can't use <code>?key=value</code> parameters, it needs to be segmented. I've tried to work with <code>add_rewrite_rule()</code>, but it doesn't seem to work.</p>
<p>How can I achieve something like that?</p>
|
[
{
"answer_id": 203601,
"author": "Raffael Lima",
"author_id": 80907,
"author_profile": "https://wordpress.stackexchange.com/users/80907",
"pm_score": 2,
"selected": false,
"text": "<p>Visual Composer adds the image ID to the generated shortcode. This gives you more flexibility with image sizes. You can use it like this:</p>\n\n<pre><code>$imageSrc = wp_get_attachment_image_src($image_url, 'thumbnail');\nif( $imageSrc ) {\n echo '<img src=\"' . $imageSrc[0] . '\" />';\n}\n</code></pre>\n\n<p>The <code>thumbnail</code> param could be replaced by <code>medium</code> or another valid image size. The <code>if</code> clause is there to verify that the image is really there (not deleted).</p>\n\n<p>Advice: Rename the <code>param_name</code> to <code>image_id</code> so you won't get confused when using the code later.</p>\n\n<p>Source: <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/</a></p>\n"
},
{
"answer_id": 241122,
"author": "mlimon",
"author_id": 64458,
"author_profile": "https://wordpress.stackexchange.com/users/64458",
"pm_score": 0,
"selected": false,
"text": "<p>Use you image url by your attachment id that already shown. So just use <code>wp_get_attachment_image_src</code> to get the attachment url. like:</p>\n\n<pre><code>add_shortcode( 'image_url', 'bild_func' );\nfunction bild_func( $atts ) {\n extract( shortcode_atts( array(\n 'image_url' => ''\n ), $atts ) );\n\n /* Let's get the URL from that image */\n if(isset($a['image_url'])) {\n $image_url = wp_get_attachment_image_src( $a['image_url'], 'full' );;\n } else {\n $image_url = ''; // default image or something if you want.\n }\n\n return \"<div class='bild-wrapper'><img src='\" . \"{$image_url[0]}\" . \"'/></div>\";\n}\n</code></pre>\n\n<p>Hope it make sense !</p>\n"
},
{
"answer_id": 249102,
"author": "Philipp Schreiber",
"author_id": 21406,
"author_profile": "https://wordpress.stackexchange.com/users/21406",
"pm_score": 0,
"selected": false,
"text": "<p>Visual Composer does the right thing with providing the image id because you can the get the image in the best size for your needs. You could do it like that:</p>\n\n<pre><code>// Replace 'thumbnail' with any valid wordpress image size.\n$imageSrc = wp_get_attachment_image_src($image_url, 'thumbnail'); \n// Check if the image is still there\nif( $imageSrc ) {\n echo '<img src=\"' . $imageSrc[0] . '\" />';\n}\n</code></pre>\n\n<p>You could also rename the 'param_name' in 'vc_map' to 'image_id' so you understand the code later.</p>\n"
}
] |
2015/07/19
|
[
"https://wordpress.stackexchange.com/questions/194983",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76437/"
] |
I need to add a custom parameter/segment to the post URL.
For example, when I have a post at `example.com/post-name`, I need to add another segment like `example.com/post-name/places`. After that, I need to add a dynamic segment like `example.com/post-name/places/dynamic-value`.
I can't use `?key=value` parameters, it needs to be segmented. I've tried to work with `add_rewrite_rule()`, but it doesn't seem to work.
How can I achieve something like that?
|
Visual Composer adds the image ID to the generated shortcode. This gives you more flexibility with image sizes. You can use it like this:
```
$imageSrc = wp_get_attachment_image_src($image_url, 'thumbnail');
if( $imageSrc ) {
echo '<img src="' . $imageSrc[0] . '" />';
}
```
The `thumbnail` param could be replaced by `medium` or another valid image size. The `if` clause is there to verify that the image is really there (not deleted).
Advice: Rename the `param_name` to `image_id` so you won't get confused when using the code later.
Source: <https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/>
|
194,987 |
<p>I have woocommerce page for my products that is treated like an archive page. I need to get the ID for the archive page but obviously if I use <code>$post->ID</code> or <code>get_the_id()</code>, etc. I get the id for the most recent post on that page.</p>
|
[
{
"answer_id": 194988,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": false,
"text": "<p>If this is a true page, then you can get the ID of that specific page with <code>get_queried_object_id()</code>. This works and will return the ID on the specific pages, single, category, taxonomy, tag and author pages where it is used. True date and time archives and the homepage will <strong>not</strong> have ID's</p>\n\n<p>You can do the following</p>\n\n<pre><code>$page_id = get_queried_object_id();\necho $page_id;\n</code></pre>\n\n<p>Just one very important note, <code>query_posts</code> breaks the main query which breaks the functionality above. This will lead to incorrect data. So make sure that you never ever use <code>query_posts</code></p>\n"
},
{
"answer_id": 195002,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": false,
"text": "<p>Do you really need to know the ID, for that see @PieterGoosens's answer, or do you just need to know if you are at the post type <code>product</code> archive? The latter can easily be achieved by using <a href=\"https://codex.wordpress.org/Function_Reference/is_post_type_archive\" rel=\"nofollow\"><code>is_post_type_archive()</code></a>:</p>\n\n<pre><code>if ( is_post_type_archive( 'product' ) ) {\n // code\n}\n</code></pre>\n"
}
] |
2015/07/20
|
[
"https://wordpress.stackexchange.com/questions/194987",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8278/"
] |
I have woocommerce page for my products that is treated like an archive page. I need to get the ID for the archive page but obviously if I use `$post->ID` or `get_the_id()`, etc. I get the id for the most recent post on that page.
|
If this is a true page, then you can get the ID of that specific page with `get_queried_object_id()`. This works and will return the ID on the specific pages, single, category, taxonomy, tag and author pages where it is used. True date and time archives and the homepage will **not** have ID's
You can do the following
```
$page_id = get_queried_object_id();
echo $page_id;
```
Just one very important note, `query_posts` breaks the main query which breaks the functionality above. This will lead to incorrect data. So make sure that you never ever use `query_posts`
|
194,997 |
<p>Recently clean-installed (with exception of themes and content/upload folders) an old wordpress to the latest Wordpress 4.2.2.</p>
<p>I continue to get this error below whenever I load files such as style.css in the web browser manually. </p>
<p>I've tried:</p>
<ul>
<li>changing this file's permission to 644, 755, and 777</li>
<li>changing .c to .so in the .htaccess</li>
<li>changing htaccess permission from 644 to 755 to even 777.</li>
<li>adding mod_sec clause to htaccess</li>
</ul>
<p>None of the above works for me. This error still occurs? I'm running PHP 5.4.43 and Wordpress 4.2.2.</p>
<pre>
Forbidden
You don't have permission to access /blog/wp-content/themes/wp-knowledge-base/style.css on this server.
Server unable to read htaccess file, denying access to be safe
Apache/2.4.12 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4 Server at subdomain.domain.com Port 80
</pre>
|
[
{
"answer_id": 194988,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": false,
"text": "<p>If this is a true page, then you can get the ID of that specific page with <code>get_queried_object_id()</code>. This works and will return the ID on the specific pages, single, category, taxonomy, tag and author pages where it is used. True date and time archives and the homepage will <strong>not</strong> have ID's</p>\n\n<p>You can do the following</p>\n\n<pre><code>$page_id = get_queried_object_id();\necho $page_id;\n</code></pre>\n\n<p>Just one very important note, <code>query_posts</code> breaks the main query which breaks the functionality above. This will lead to incorrect data. So make sure that you never ever use <code>query_posts</code></p>\n"
},
{
"answer_id": 195002,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": false,
"text": "<p>Do you really need to know the ID, for that see @PieterGoosens's answer, or do you just need to know if you are at the post type <code>product</code> archive? The latter can easily be achieved by using <a href=\"https://codex.wordpress.org/Function_Reference/is_post_type_archive\" rel=\"nofollow\"><code>is_post_type_archive()</code></a>:</p>\n\n<pre><code>if ( is_post_type_archive( 'product' ) ) {\n // code\n}\n</code></pre>\n"
}
] |
2015/07/20
|
[
"https://wordpress.stackexchange.com/questions/194997",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76447/"
] |
Recently clean-installed (with exception of themes and content/upload folders) an old wordpress to the latest Wordpress 4.2.2.
I continue to get this error below whenever I load files such as style.css in the web browser manually.
I've tried:
* changing this file's permission to 644, 755, and 777
* changing .c to .so in the .htaccess
* changing htaccess permission from 644 to 755 to even 777.
* adding mod\_sec clause to htaccess
None of the above works for me. This error still occurs? I'm running PHP 5.4.43 and Wordpress 4.2.2.
```
Forbidden
You don't have permission to access /blog/wp-content/themes/wp-knowledge-base/style.css on this server.
Server unable to read htaccess file, denying access to be safe
Apache/2.4.12 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4 Server at subdomain.domain.com Port 80
```
|
If this is a true page, then you can get the ID of that specific page with `get_queried_object_id()`. This works and will return the ID on the specific pages, single, category, taxonomy, tag and author pages where it is used. True date and time archives and the homepage will **not** have ID's
You can do the following
```
$page_id = get_queried_object_id();
echo $page_id;
```
Just one very important note, `query_posts` breaks the main query which breaks the functionality above. This will lead to incorrect data. So make sure that you never ever use `query_posts`
|
195,000 |
<p>I'm running a WordPress site and wanna setup a mobile site based on it. </p>
<p>I've tried some plugins like Mobile Themes which allows me to implement a different theme for mobile. The problem is when I use memcached, the main theme and mobile theme is confusing very often(e.g. access the site by mobile but meet a main theme)</p>
<p>I'm considering another way to do this now. Use a PHP mobile detective script, and write the code in all theme template files(e.g. <code>header.php</code>) like:</p>
<pre><code>if(is_mobile()) {
// mobile theme code
} else {
// main theme code
}
</code></pre>
<p>for this, I need only to maintain one theme. I've never tried this way, not sure if there is any problem, and I didn't think about how to handle the style.css yet.(There are some plugins allow me to use different style rules for mobile, but I've never tried)</p>
<p>Does anybody could provide some suggestions?</p>
|
[
{
"answer_id": 194988,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": false,
"text": "<p>If this is a true page, then you can get the ID of that specific page with <code>get_queried_object_id()</code>. This works and will return the ID on the specific pages, single, category, taxonomy, tag and author pages where it is used. True date and time archives and the homepage will <strong>not</strong> have ID's</p>\n\n<p>You can do the following</p>\n\n<pre><code>$page_id = get_queried_object_id();\necho $page_id;\n</code></pre>\n\n<p>Just one very important note, <code>query_posts</code> breaks the main query which breaks the functionality above. This will lead to incorrect data. So make sure that you never ever use <code>query_posts</code></p>\n"
},
{
"answer_id": 195002,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": false,
"text": "<p>Do you really need to know the ID, for that see @PieterGoosens's answer, or do you just need to know if you are at the post type <code>product</code> archive? The latter can easily be achieved by using <a href=\"https://codex.wordpress.org/Function_Reference/is_post_type_archive\" rel=\"nofollow\"><code>is_post_type_archive()</code></a>:</p>\n\n<pre><code>if ( is_post_type_archive( 'product' ) ) {\n // code\n}\n</code></pre>\n"
}
] |
2015/07/20
|
[
"https://wordpress.stackexchange.com/questions/195000",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75850/"
] |
I'm running a WordPress site and wanna setup a mobile site based on it.
I've tried some plugins like Mobile Themes which allows me to implement a different theme for mobile. The problem is when I use memcached, the main theme and mobile theme is confusing very often(e.g. access the site by mobile but meet a main theme)
I'm considering another way to do this now. Use a PHP mobile detective script, and write the code in all theme template files(e.g. `header.php`) like:
```
if(is_mobile()) {
// mobile theme code
} else {
// main theme code
}
```
for this, I need only to maintain one theme. I've never tried this way, not sure if there is any problem, and I didn't think about how to handle the style.css yet.(There are some plugins allow me to use different style rules for mobile, but I've never tried)
Does anybody could provide some suggestions?
|
If this is a true page, then you can get the ID of that specific page with `get_queried_object_id()`. This works and will return the ID on the specific pages, single, category, taxonomy, tag and author pages where it is used. True date and time archives and the homepage will **not** have ID's
You can do the following
```
$page_id = get_queried_object_id();
echo $page_id;
```
Just one very important note, `query_posts` breaks the main query which breaks the functionality above. This will lead to incorrect data. So make sure that you never ever use `query_posts`
|
195,025 |
<p>I have a post and payment page
each posts contain a payment form</p>
<p>I want to know how I can retrieve the data to I can execute and publish where the post payment came from</p>
<p>on payment form submit</p>
<pre><code> $return = array('success' => true, 'msg' => 'Payment Successful',
'current_post_id' => get_the_ID(),'payment_made' => true);
</code></pre>
<p>then payment page</p>
<pre><code>function enable_post($current_post_id) {
if (payment_made =='true') {
/* Execute a Jquery that would affect the post */
/* Make post Publish instead of draft*/
} }
</code></pre>
|
[
{
"answer_id": 194988,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": false,
"text": "<p>If this is a true page, then you can get the ID of that specific page with <code>get_queried_object_id()</code>. This works and will return the ID on the specific pages, single, category, taxonomy, tag and author pages where it is used. True date and time archives and the homepage will <strong>not</strong> have ID's</p>\n\n<p>You can do the following</p>\n\n<pre><code>$page_id = get_queried_object_id();\necho $page_id;\n</code></pre>\n\n<p>Just one very important note, <code>query_posts</code> breaks the main query which breaks the functionality above. This will lead to incorrect data. So make sure that you never ever use <code>query_posts</code></p>\n"
},
{
"answer_id": 195002,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": false,
"text": "<p>Do you really need to know the ID, for that see @PieterGoosens's answer, or do you just need to know if you are at the post type <code>product</code> archive? The latter can easily be achieved by using <a href=\"https://codex.wordpress.org/Function_Reference/is_post_type_archive\" rel=\"nofollow\"><code>is_post_type_archive()</code></a>:</p>\n\n<pre><code>if ( is_post_type_archive( 'product' ) ) {\n // code\n}\n</code></pre>\n"
}
] |
2015/07/20
|
[
"https://wordpress.stackexchange.com/questions/195025",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44422/"
] |
I have a post and payment page
each posts contain a payment form
I want to know how I can retrieve the data to I can execute and publish where the post payment came from
on payment form submit
```
$return = array('success' => true, 'msg' => 'Payment Successful',
'current_post_id' => get_the_ID(),'payment_made' => true);
```
then payment page
```
function enable_post($current_post_id) {
if (payment_made =='true') {
/* Execute a Jquery that would affect the post */
/* Make post Publish instead of draft*/
} }
```
|
If this is a true page, then you can get the ID of that specific page with `get_queried_object_id()`. This works and will return the ID on the specific pages, single, category, taxonomy, tag and author pages where it is used. True date and time archives and the homepage will **not** have ID's
You can do the following
```
$page_id = get_queried_object_id();
echo $page_id;
```
Just one very important note, `query_posts` breaks the main query which breaks the functionality above. This will lead to incorrect data. So make sure that you never ever use `query_posts`
|
195,032 |
<p>Im having an issue if i want to login to the dashboard, it needs a "Database Update Required"</p>
<p>I'd like to disable it, because once it update the Database, if I go to any post of single-pages, it display all my post in loop . .. . If i recover my database before this update - everything is working correctly.</p>
<p>Any Idea where is this coming from ? or how to disable this update require ?</p>
<p>It will be greatfull,</p>
<p>Thank you for your time,</p>
|
[
{
"answer_id": 195058,
"author": "xyulex",
"author_id": 76474,
"author_profile": "https://wordpress.stackexchange.com/users/76474",
"pm_score": 1,
"selected": false,
"text": "<p>If you get that Database update message, looks like WordPress may have updated.</p>\n\n<p>Probably you want to turn automatic updates off.</p>\n\n<h2>Simply do:</h2>\n\n<p>1 - Restore your db where it works ok</p>\n\n<p>2 - Add this to your <code>wp-config.php</code>: </p>\n\n<pre><code>define( 'AUTOMATIC_UPDATER_DISABLED', true );\n</code></pre>\n\n<p>3 - Enjoy!</p>\n"
},
{
"answer_id": 195266,
"author": "tibewww",
"author_id": 54146,
"author_profile": "https://wordpress.stackexchange.com/users/54146",
"pm_score": 0,
"selected": false,
"text": "<p>I finally got it by changing the db value in <code>wp_options</code> table and it works like a charm</p>\n"
}
] |
2015/07/20
|
[
"https://wordpress.stackexchange.com/questions/195032",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54146/"
] |
Im having an issue if i want to login to the dashboard, it needs a "Database Update Required"
I'd like to disable it, because once it update the Database, if I go to any post of single-pages, it display all my post in loop . .. . If i recover my database before this update - everything is working correctly.
Any Idea where is this coming from ? or how to disable this update require ?
It will be greatfull,
Thank you for your time,
|
If you get that Database update message, looks like WordPress may have updated.
Probably you want to turn automatic updates off.
Simply do:
----------
1 - Restore your db where it works ok
2 - Add this to your `wp-config.php`:
```
define( 'AUTOMATIC_UPDATER_DISABLED', true );
```
3 - Enjoy!
|
195,053 |
<p>I am using <a href="https://wordpress.org/plugins/wp-pagenavi/" rel="nofollow">WP-PageNavi</a> pagination and because of certain reasons I have "Blog pages show at most" set to 100 and I can't reduce it. </p>
<p>I have a total of 30 posts in a category. I want to display 10 posts on each page but it doesn't display pagination; it displays only if a category has more then 100 posts. Code is below:</p>
<pre><code>$cat_id = get_query_var( 'cat' );
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$found_posts = array(
'posts_per_page' => 10,
'cat' => $cat_id,
'meta_key' => "custom_key",
'meta_value' => '',
'meta_compare' => '!=',
'ignore_sticky_posts' => 1,
'orderby' => 'meta_value_num', // or 'meta_value_num'
'order' => "DESC",
'paged' => $paged
);
$loop = new WP_Query( $found_posts );
while( $loop->have_posts() ): $loop->the_post();
global $post;
// Loop Here
endwhile;
wp_reset_query();
if ( function_exists( 'wp_pagenavi' ) ) {
wp_pagenavi();
}
</code></pre>
|
[
{
"answer_id": 195060,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>Do not run custom queries in place of the main query on the home page and any type of archive page. This will always cause an issue. If you need to alter the main query, use <code>pre_get_posts</code> to do so. </p>\n\n<p>To solve this issue, you need remove your code from your category page and go back to the default loop. You should only have the following in your category page</p>\n\n<pre><code>if ( have_posts() ) {\n while ( have_posts() ) {\n the_post();\n // YOUR MARKUP AND TEMPLATE TAGS\n }\n}\n</code></pre>\n\n<p>This will led that you will see all category posts on the category post ordered by post date. As I said, you now need to use <code>pre_get_posts</code> to alter the main query on category pages to set your custom ordering and pagination</p>\n\n<p>You need to add the following in <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 queries\n && $q->is_main_query() // Targets the main query only\n && $q->is_category() // Only target category pages\n ) {\n $q->set( 'posts_per_page', 10 );\n $q->set( 'meta_key', 'custom_key' );\n $q->set( 'meta_value', '' );\n $q->set( 'meta_compare', '!=' );\n $q->set( 'orderby', 'meta_value_num' );\n $q->set( 'ignore_sticky_posts', 1 );\n }\n});\n</code></pre>\n\n<p>You should no see 10 posts per page ordered by <code>meta_value_num</code> from the custom field <code>custom_key</code> sorted highest to lowest on your category pages</p>\n"
},
{
"answer_id": 203242,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 1,
"selected": false,
"text": "<p>In addition to the \"selected answer\", this might be needed:</p>\n\n<pre><code>$q->set( 'post_type', get_post_types() );\n</code></pre>\n"
}
] |
2015/07/20
|
[
"https://wordpress.stackexchange.com/questions/195053",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/36035/"
] |
I am using [WP-PageNavi](https://wordpress.org/plugins/wp-pagenavi/) pagination and because of certain reasons I have "Blog pages show at most" set to 100 and I can't reduce it.
I have a total of 30 posts in a category. I want to display 10 posts on each page but it doesn't display pagination; it displays only if a category has more then 100 posts. Code is below:
```
$cat_id = get_query_var( 'cat' );
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$found_posts = array(
'posts_per_page' => 10,
'cat' => $cat_id,
'meta_key' => "custom_key",
'meta_value' => '',
'meta_compare' => '!=',
'ignore_sticky_posts' => 1,
'orderby' => 'meta_value_num', // or 'meta_value_num'
'order' => "DESC",
'paged' => $paged
);
$loop = new WP_Query( $found_posts );
while( $loop->have_posts() ): $loop->the_post();
global $post;
// Loop Here
endwhile;
wp_reset_query();
if ( function_exists( 'wp_pagenavi' ) ) {
wp_pagenavi();
}
```
|
Do not run custom queries in place of the main query on the home page and any type of archive page. This will always cause an issue. If you need to alter the main query, use `pre_get_posts` to do so.
To solve this issue, you need remove your code from your category page and go back to the default loop. You should only have the following in your category page
```
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
// YOUR MARKUP AND TEMPLATE TAGS
}
}
```
This will led that you will see all category posts on the category post ordered by post date. As I said, you now need to use `pre_get_posts` to alter the main query on category pages to set your custom ordering and pagination
You need to add the following in `functions.php`
```
add_action( 'pre_get_posts', function ( $q )
{
if ( !is_admin() // Only target the front end queries
&& $q->is_main_query() // Targets the main query only
&& $q->is_category() // Only target category pages
) {
$q->set( 'posts_per_page', 10 );
$q->set( 'meta_key', 'custom_key' );
$q->set( 'meta_value', '' );
$q->set( 'meta_compare', '!=' );
$q->set( 'orderby', 'meta_value_num' );
$q->set( 'ignore_sticky_posts', 1 );
}
});
```
You should no see 10 posts per page ordered by `meta_value_num` from the custom field `custom_key` sorted highest to lowest on your category pages
|
195,067 |
<p>Version 4.2.1 of WordPress removed the link text from the Insert/edit link box. </p>
<p>How can i add it back?</p>
|
[
{
"answer_id": 195060,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>Do not run custom queries in place of the main query on the home page and any type of archive page. This will always cause an issue. If you need to alter the main query, use <code>pre_get_posts</code> to do so. </p>\n\n<p>To solve this issue, you need remove your code from your category page and go back to the default loop. You should only have the following in your category page</p>\n\n<pre><code>if ( have_posts() ) {\n while ( have_posts() ) {\n the_post();\n // YOUR MARKUP AND TEMPLATE TAGS\n }\n}\n</code></pre>\n\n<p>This will led that you will see all category posts on the category post ordered by post date. As I said, you now need to use <code>pre_get_posts</code> to alter the main query on category pages to set your custom ordering and pagination</p>\n\n<p>You need to add the following in <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 queries\n && $q->is_main_query() // Targets the main query only\n && $q->is_category() // Only target category pages\n ) {\n $q->set( 'posts_per_page', 10 );\n $q->set( 'meta_key', 'custom_key' );\n $q->set( 'meta_value', '' );\n $q->set( 'meta_compare', '!=' );\n $q->set( 'orderby', 'meta_value_num' );\n $q->set( 'ignore_sticky_posts', 1 );\n }\n});\n</code></pre>\n\n<p>You should no see 10 posts per page ordered by <code>meta_value_num</code> from the custom field <code>custom_key</code> sorted highest to lowest on your category pages</p>\n"
},
{
"answer_id": 203242,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 1,
"selected": false,
"text": "<p>In addition to the \"selected answer\", this might be needed:</p>\n\n<pre><code>$q->set( 'post_type', get_post_types() );\n</code></pre>\n"
}
] |
2015/07/20
|
[
"https://wordpress.stackexchange.com/questions/195067",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76479/"
] |
Version 4.2.1 of WordPress removed the link text from the Insert/edit link box.
How can i add it back?
|
Do not run custom queries in place of the main query on the home page and any type of archive page. This will always cause an issue. If you need to alter the main query, use `pre_get_posts` to do so.
To solve this issue, you need remove your code from your category page and go back to the default loop. You should only have the following in your category page
```
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
// YOUR MARKUP AND TEMPLATE TAGS
}
}
```
This will led that you will see all category posts on the category post ordered by post date. As I said, you now need to use `pre_get_posts` to alter the main query on category pages to set your custom ordering and pagination
You need to add the following in `functions.php`
```
add_action( 'pre_get_posts', function ( $q )
{
if ( !is_admin() // Only target the front end queries
&& $q->is_main_query() // Targets the main query only
&& $q->is_category() // Only target category pages
) {
$q->set( 'posts_per_page', 10 );
$q->set( 'meta_key', 'custom_key' );
$q->set( 'meta_value', '' );
$q->set( 'meta_compare', '!=' );
$q->set( 'orderby', 'meta_value_num' );
$q->set( 'ignore_sticky_posts', 1 );
}
});
```
You should no see 10 posts per page ordered by `meta_value_num` from the custom field `custom_key` sorted highest to lowest on your category pages
|
195,087 |
<p>I'm using WordPress 4.2.2 and every time I add an image to the wysiwyg it wraps the outputed image in a paragraph tag. I need to strip out these tags. Everything I seem to find online is from 2011 plus it doesn't seem to work.</p>
<p>I have tried putting things in the functions.php like:</p>
<pre><code>function filter_ptags_on_images($content){
return preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
}
add_filter('the_content', 'filter_ptags_on_images');
</code></pre>
<p>Nothing seems to work. How can I accomplish this. </p>
<p>BTW I am using ACF Pro's wysiwyg and JointsWP starter theme and my images ARE NOT wrapped in a link tag if that makes a difference.</p>
|
[
{
"answer_id": 195097,
"author": "Bryan Willis",
"author_id": 38123,
"author_profile": "https://wordpress.stackexchange.com/users/38123",
"pm_score": 4,
"selected": true,
"text": "<p><strong>1) Filter wpautop() with ACF:</strong></p>\n\n<pre><code>function filter_ptags_on_images($content) {\n $content = preg_replace('/<p>\\s*(<a .*>)?\\s*(<img .* \\/>)\\s*(<\\/a>)?\\s*<\\/p>/iU', '\\1\\2\\3', $content);\n return preg_replace('/<p>\\s*(<iframe .*>*.<\\/iframe>)\\s*<\\/p>/iU', '\\1', $content);\n}\nadd_filter('acf_the_content', 'filter_ptags_on_images');\nadd_filter('the_content', 'filter_ptags_on_images');\n</code></pre>\n\n<p>If you have both of those try checking with a later priority on the add_filter. It's possible the theme or plugin or acf is overriding you....</p>\n\n<pre><code>add_filter('acf_the_content', 'filter_ptags_on_images', 9999);\nadd_filter('the_content', 'filter_ptags_on_images', 9999);\n</code></pre>\n\n<p><strong>2) Edit wpautop():</strong></p>\n\n<pre><code><?php\nremove_filter( 'the_content', 'wpautop' );\nadd_filter( 'the_content', 'custom_wpautop' );\nfunction custom_wpautop() {\n // copy wpautop() code at https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/formatting.php#L373 and add img to the $allblocks variable\n}\n</code></pre>\n\n<p><strong>3) This above is a lot of code for one task however. Consider trying this:</strong>\n<a href=\"https://wordpress.org/plugins/preserved-html-editor-markup-plus\" rel=\"noreferrer\">https://wordpress.org/plugins/preserved-html-editor-markup-plus</a></p>\n\n<p><strong>4) You could try this although not as good as the method you're trying to accomplish since this one is done with javascript.</strong></p>\n\n<pre><code><script type=\"text/javascript\">\njQuery(document).ready(function($){\n $('p > img').unwrap();\n});\n</script>\n</code></pre>\n\n<p><strong>5) if it's just the styling that's messing things up and you don't care about the markup:</strong></p>\n\n<pre><code><style type=\"text/css\">\np > img {\n margin: 0 !important;\n}\n</style>\n</code></pre>\n"
},
{
"answer_id": 369025,
"author": "Nuno Sarmento",
"author_id": 75461,
"author_profile": "https://wordpress.stackexchange.com/users/75461",
"pm_score": 0,
"selected": false,
"text": "<p>I use the acf_the_content filter to preg_replace the p tag. The below code will replace the p tag and wrap the image inside a div</p>\n<pre><code>/**\n * Remove P tags from images\n */\nfunction ns_img_unautop($custom_content) {\n $custom_content = preg_replace('/<p>\\\\s*?(<a .*?><img.*?><\\\\/a>|<img.*?>)?\\\\s*<\\\\/p>/s', '<div class="figure">$1</div>', $custom_content);\n return $custom_content;\n}\nadd_filter( 'acf_the_content', 'ns_img_unautop', 30 );\n</code></pre>\n"
}
] |
2015/07/20
|
[
"https://wordpress.stackexchange.com/questions/195087",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/56854/"
] |
I'm using WordPress 4.2.2 and every time I add an image to the wysiwyg it wraps the outputed image in a paragraph tag. I need to strip out these tags. Everything I seem to find online is from 2011 plus it doesn't seem to work.
I have tried putting things in the functions.php like:
```
function filter_ptags_on_images($content){
return preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
}
add_filter('the_content', 'filter_ptags_on_images');
```
Nothing seems to work. How can I accomplish this.
BTW I am using ACF Pro's wysiwyg and JointsWP starter theme and my images ARE NOT wrapped in a link tag if that makes a difference.
|
**1) Filter wpautop() with ACF:**
```
function filter_ptags_on_images($content) {
$content = preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
return preg_replace('/<p>\s*(<iframe .*>*.<\/iframe>)\s*<\/p>/iU', '\1', $content);
}
add_filter('acf_the_content', 'filter_ptags_on_images');
add_filter('the_content', 'filter_ptags_on_images');
```
If you have both of those try checking with a later priority on the add\_filter. It's possible the theme or plugin or acf is overriding you....
```
add_filter('acf_the_content', 'filter_ptags_on_images', 9999);
add_filter('the_content', 'filter_ptags_on_images', 9999);
```
**2) Edit wpautop():**
```
<?php
remove_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'custom_wpautop' );
function custom_wpautop() {
// copy wpautop() code at https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/formatting.php#L373 and add img to the $allblocks variable
}
```
**3) This above is a lot of code for one task however. Consider trying this:**
<https://wordpress.org/plugins/preserved-html-editor-markup-plus>
**4) You could try this although not as good as the method you're trying to accomplish since this one is done with javascript.**
```
<script type="text/javascript">
jQuery(document).ready(function($){
$('p > img').unwrap();
});
</script>
```
**5) if it's just the styling that's messing things up and you don't care about the markup:**
```
<style type="text/css">
p > img {
margin: 0 !important;
}
</style>
```
|
195,196 |
<p>I am trying to change default Gravatar size. Since I am using WP-generated comments template (using comments_template() function), I turned to filters and this is my custom code:</p>
<pre><code>function change_avatar_size ( $id_or_email, $size = 100, $default = '', $alt = '', $args = null ) {
$args['size'] = (int) $size;
$url2x = get_avatar_url( $id_or_email, array_merge( $args, array( 'size' => $args['size'] * 2 ) ) );
$args = get_avatar_data( $id_or_email, $args );
$url = $args['url'];
$class = array( 'avatar', 'avatar-' . (int) $args['size'], 'photo' );
$avatar = sprintf(
"<img alt='%s' src='%s' srcset='%s' class='%s' height='%d' width='%d' %s/>",
esc_attr( $args['alt'] ),
esc_url( $url ),
esc_attr( "$url2x 2x" ),
esc_attr( join( ' ', $class ) ),
(int) $args['height'],
(int) $args['width'],
$args['extra_attr']
);
return $avatar;
}
add_filter( 'get_avatar', 'change_avatar_size' );
</code></pre>
<p>The size does change, but I am not getting the correct Gravatar URL. I am getting default Gravatar image actually, as if the generated link is not correct. Any ideas?</p>
|
[
{
"answer_id": 195268,
"author": "Bruno Kos",
"author_id": 19499,
"author_profile": "https://wordpress.stackexchange.com/users/19499",
"pm_score": 0,
"selected": false,
"text": "<p>Found it - no need to bother with filters, given that there is avatar_size parameter within wp_list_comments, it can be found here: <a href=\"https://developer.wordpress.org/reference/functions/wp_list_comments/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/wp_list_comments/</a></p>\n"
},
{
"answer_id": 210636,
"author": "Bryan Willis",
"author_id": 38123,
"author_profile": "https://wordpress.stackexchange.com/users/38123",
"pm_score": 2,
"selected": false,
"text": "<p>Here's how to do it using the method Bruno went with (for others wondering this):</p>\n\n<pre><code>wp_list_comments( array(\n 'avatar_size' => 32\n) );\n</code></pre>\n\n<p>You can also do it <a href=\"https://wordpress.stackexchange.com/a/210633/43806\">this way</a> depending on your use case:</p>\n\n<pre><code>global $comment;\necho get_avatar($comment, 64)\n</code></pre>\n"
}
] |
2015/07/21
|
[
"https://wordpress.stackexchange.com/questions/195196",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/19499/"
] |
I am trying to change default Gravatar size. Since I am using WP-generated comments template (using comments\_template() function), I turned to filters and this is my custom code:
```
function change_avatar_size ( $id_or_email, $size = 100, $default = '', $alt = '', $args = null ) {
$args['size'] = (int) $size;
$url2x = get_avatar_url( $id_or_email, array_merge( $args, array( 'size' => $args['size'] * 2 ) ) );
$args = get_avatar_data( $id_or_email, $args );
$url = $args['url'];
$class = array( 'avatar', 'avatar-' . (int) $args['size'], 'photo' );
$avatar = sprintf(
"<img alt='%s' src='%s' srcset='%s' class='%s' height='%d' width='%d' %s/>",
esc_attr( $args['alt'] ),
esc_url( $url ),
esc_attr( "$url2x 2x" ),
esc_attr( join( ' ', $class ) ),
(int) $args['height'],
(int) $args['width'],
$args['extra_attr']
);
return $avatar;
}
add_filter( 'get_avatar', 'change_avatar_size' );
```
The size does change, but I am not getting the correct Gravatar URL. I am getting default Gravatar image actually, as if the generated link is not correct. Any ideas?
|
Here's how to do it using the method Bruno went with (for others wondering this):
```
wp_list_comments( array(
'avatar_size' => 32
) );
```
You can also do it [this way](https://wordpress.stackexchange.com/a/210633/43806) depending on your use case:
```
global $comment;
echo get_avatar($comment, 64)
```
|
195,221 |
<p>This seems to be common issue, and there exist a lot of posts about this issue but none of them works for me.</p>
<p>I have a custom post type (portfolio) with a page pagination.</p>
<pre><code>$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
echo '<a href="'.get_pagenum_link($paged+1).'">Next Page</a>';
</code></pre>
<p>When Set the permalinks settings to 'Default' it works fine. </p>
<p><strong>mysite.com/?page_id=111&paged=2</strong></p>
<p>When Set the permalinks to any custom structure it leads to the 404 page. </p>
<p><strong>mysite.com/portfolio/page/2/</strong></p>
<p>This is driving me crazy. Can't find any solution. I don't have a page or post which have the slugname 'page', so this can't be the problem. I refreshed the permlinks multiple times, which doesn't work either.</p>
<p>NB: default Blog page works fine for both permalinks settings</p>
<p>I would really appreciate some hlep on this.
Thanks</p>
|
[
{
"answer_id": 196671,
"author": "Jose Andres Cordova",
"author_id": 77309,
"author_profile": "https://wordpress.stackexchange.com/users/77309",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same case and I was going crazy and tested\nDisable canonical redirection for this case and worked. Maybe this will also help</p>\n\n<p>I'm not sure if this would be the best way to do this , however.</p>\n\n<pre><code>function no_canonical( $url ) {\n return false;\n}\nfunction adjust_show_request( $request ) {\n if ($request->query_vars['post_type'] === 'agent' && $request->is_singular === true && $request->current_post == -1 && $request->is_paged === true ) {\n add_filter( 'redirect_canonical', 'no_canonical' );\n }\n return $request;\n}\nadd_action( 'parse_query', 'adjust_show_request' );\n</code></pre>\n"
},
{
"answer_id": 288937,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 0,
"selected": false,
"text": "<p>try with this for page pagination. your page next previous order depends on menu order. check get_pages arg. code put into your theme page template.</p>\n\n<pre><code><?php\n$pagelist = get_pages('sort_column=menu_order&sort_order=asc');\n$pages = array();\nforeach ($pagelist as $page) {\n $pages[] += $page->ID;\n}\n\n$current = array_search(get_the_ID(), $pages);\n$prevID = $pages[$current-1];\n$nextID = $pages[$current+1];\n?>\n\n<div class=\"navigation\">\n<?php if (!empty($prevID)) { ?>\n<div class=\"alignleft\">\n<a href=\"<?php echo get_permalink($prevID); ?>\"\n title=\"<?php echo get_the_title($prevID); ?>\">Previous</a>\n</div>\n<?php }\nif (!empty($nextID)) { ?>\n<div class=\"alignright\">\n<a href=\"<?php echo get_permalink($nextID); ?>\" \n title=\"<?php echo get_the_title($nextID); ?>\">Next</a>\n</div>\n<?php } ?>\n</div>\n</code></pre>\n"
},
{
"answer_id": 294463,
"author": "Nasir Uddin",
"author_id": 132640,
"author_profile": "https://wordpress.stackexchange.com/users/132640",
"pm_score": 1,
"selected": false,
"text": "<p>Paste this function to your <code>functions.php</code> file</p>\n\n<pre><code>if ( ! function_exists( 'custom_pagination' ) ) {\n function custom_pagination( $query_args ) {\n $big = 999999999; // need an unlikely integer\n $pages = paginate_links( array(\n 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' => '?paged=%#%',\n 'current' => max( 1, get_query_var( 'paged' ) ),\n 'total' => $query_args->max_num_pages,\n 'prev_next' => false,\n 'type' => 'array',\n 'prev_next' => true,\n 'prev_text' => __('«'),\n 'next_text' => __('»'),\n ) );\n if ( is_array( $pages ) ) {\n $paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var('paged');\n echo '<ul class=\"pagination\">';\n foreach ( $pages as $page ) {\n echo \"<li>$page</li>\";\n }\n echo '</ul>';\n }\n }\n}\n</code></pre>\n\n<p>Then on your custom post loop page write the loop as </p>\n\n<pre><code>$args = [\n 'post_type' => 'post',\n 'posts_per_page' => get_option('posts_per_page'),\n];\n\n$query = new WP_Query( $args );\n\nif ( $query->have_posts() ) {\n while ( $query->have_posts() ) {\n $query->the_post();\n // You content goes here\n }\n custom_pagination( $query );\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>This works fine for me. </p>\n"
}
] |
2015/07/22
|
[
"https://wordpress.stackexchange.com/questions/195221",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28159/"
] |
This seems to be common issue, and there exist a lot of posts about this issue but none of them works for me.
I have a custom post type (portfolio) with a page pagination.
```
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
echo '<a href="'.get_pagenum_link($paged+1).'">Next Page</a>';
```
When Set the permalinks settings to 'Default' it works fine.
**mysite.com/?page\_id=111&paged=2**
When Set the permalinks to any custom structure it leads to the 404 page.
**mysite.com/portfolio/page/2/**
This is driving me crazy. Can't find any solution. I don't have a page or post which have the slugname 'page', so this can't be the problem. I refreshed the permlinks multiple times, which doesn't work either.
NB: default Blog page works fine for both permalinks settings
I would really appreciate some hlep on this.
Thanks
|
Paste this function to your `functions.php` file
```
if ( ! function_exists( 'custom_pagination' ) ) {
function custom_pagination( $query_args ) {
$big = 999999999; // need an unlikely integer
$pages = paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var( 'paged' ) ),
'total' => $query_args->max_num_pages,
'prev_next' => false,
'type' => 'array',
'prev_next' => true,
'prev_text' => __('«'),
'next_text' => __('»'),
) );
if ( is_array( $pages ) ) {
$paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var('paged');
echo '<ul class="pagination">';
foreach ( $pages as $page ) {
echo "<li>$page</li>";
}
echo '</ul>';
}
}
}
```
Then on your custom post loop page write the loop as
```
$args = [
'post_type' => 'post',
'posts_per_page' => get_option('posts_per_page'),
];
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// You content goes here
}
custom_pagination( $query );
wp_reset_postdata();
}
```
This works fine for me.
|
195,318 |
<p>To include new functions we can write them in the theme's functions.php. But I have to write my own functions in a new file rather altering the theme's function.php. I can write any custom js action in footer.php, but I need to write it in other file. How can I do this? Is there any correct way to do this? </p>
|
[
{
"answer_id": 195320,
"author": "Robert hue",
"author_id": 22461,
"author_profile": "https://wordpress.stackexchange.com/users/22461",
"pm_score": 2,
"selected": true,
"text": "<p>You can simply use <code>require</code>, <code>require_once</code>, <code>include</code> or <code>include_once</code> functions to include custom PHP files in your theme.</p>\n\n<pre><code>require( 'folder/custom.php' );\n</code></pre>\n\n<p>Usually you should keep your custom PHP files in a folder.</p>\n\n<p>Developers <a href=\"https://stackoverflow.com/questions/186338/why-is-require-once-so-bad-to-use\">vote against using</a> <code>require_once</code> because it is a little slower than <code>require</code> since it requires the system to keep a log of what's already been included/required.</p>\n"
},
{
"answer_id": 195321,
"author": "Pooja Mistry",
"author_id": 71675,
"author_profile": "https://wordpress.stackexchange.com/users/71675",
"pm_score": 0,
"selected": false,
"text": "<p>For adding JavaScript code in WordPress, you can create a .js file and include it in following way, in your theme's functions.php</p>\n\n<pre><code>/**\n * Proper way to enqueue scripts\n */\nfunction theme_name_scripts() {\n\n wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );\n}\n\nadd_action( 'wp_enqueue_scripts', 'theme_name_scripts' );\n</code></pre>\n\n<p>Refer <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/07/23
|
[
"https://wordpress.stackexchange.com/questions/195318",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70398/"
] |
To include new functions we can write them in the theme's functions.php. But I have to write my own functions in a new file rather altering the theme's function.php. I can write any custom js action in footer.php, but I need to write it in other file. How can I do this? Is there any correct way to do this?
|
You can simply use `require`, `require_once`, `include` or `include_once` functions to include custom PHP files in your theme.
```
require( 'folder/custom.php' );
```
Usually you should keep your custom PHP files in a folder.
Developers [vote against using](https://stackoverflow.com/questions/186338/why-is-require-once-so-bad-to-use) `require_once` because it is a little slower than `require` since it requires the system to keep a log of what's already been included/required.
|
195,335 |
<p>This is the resulting html I want to produce with a shortcode - when editing page content in WordPress:</p>
<pre><code><div class="shadow-wrapper half-shadow im-centered">
<div class="box-shadow shadow-effect-2">
<div class="servive-block servive-block-bluemed">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nec nulla vitae lacus.
</div>
</div>
</div>
</code></pre>
<p>This is what I want to use inside of the editor box - when using the new shortcode I will define:</p>
<pre><code>[box color="bluemed"]
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nec nulla vitae lacus.
[/box]
</code></pre>
<p>The parameter being passed: color="bluemed" needs to become part of the div's class.. as in: <code><div class="servive-block servive-block-bluemed"></code> (see above example of resulting html code)</p>
<p>Here is what I have put inside of my functions.php file to try to create this new shortcode:</p>
<pre><code>function colored_box_shortcode($atts) {
extract(shortcode_atts(array(
'color' => grey,
), $atts));
return '<div class="shadow-wrapper half-shadow im-centered">
<div class="box-shadow shadow-effect-2">
<div class="servive-block servive-block-'.$color.'">';
}
add_shortcode('box', 'colored_box_shortcode');
function colored_box_end() {
return '</div>
</div>
</div>';
}
add_shortcode('/box', 'colored_box_end');
</code></pre>
<p>As you can see I set the color attribute default content to be grey, but also allowing the ability to over-ride and specify the color in the parameter that is passed from the shortcode.</p>
<p>This color then needs to become part of the class name inside of the div. So if no parameter is passed then the class name will become: "servive-block-grey". Or if I pass the parameter of color="lavendar", then the class name will become: "servive-block-lavendar".</p>
<p>Is this even possible?</p>
<p>If so.. can someone help with the code I am using.. because I am getting hundreds of errors from WordPress when I view the page.</p>
<p>Basically the errors are a repeat of these 3 (which I think is probably caused by getting a syntax error with me trying to put in the parameter inside of a class name - like this: <code>servive-block-'.$color.'</code>)</p>
<blockquote>
<p>Warning: preg_split(): Unknown modifier 'b' in C:\xampp\htdocs\CIRB\CirbWP\wp-includes\formatting.php on line 244</p>
<p>Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\CIRB\CirbWP\wp-includes\formatting.php on line 246</p>
<p>Warning: implode(): Invalid arguments passed in C:\xampp\htdocs\CIRB\CirbWP\wp-includes\formatting.php on line 297</p>
</blockquote>
<p>Thanks for any guidance!</p>
|
[
{
"answer_id": 195320,
"author": "Robert hue",
"author_id": 22461,
"author_profile": "https://wordpress.stackexchange.com/users/22461",
"pm_score": 2,
"selected": true,
"text": "<p>You can simply use <code>require</code>, <code>require_once</code>, <code>include</code> or <code>include_once</code> functions to include custom PHP files in your theme.</p>\n\n<pre><code>require( 'folder/custom.php' );\n</code></pre>\n\n<p>Usually you should keep your custom PHP files in a folder.</p>\n\n<p>Developers <a href=\"https://stackoverflow.com/questions/186338/why-is-require-once-so-bad-to-use\">vote against using</a> <code>require_once</code> because it is a little slower than <code>require</code> since it requires the system to keep a log of what's already been included/required.</p>\n"
},
{
"answer_id": 195321,
"author": "Pooja Mistry",
"author_id": 71675,
"author_profile": "https://wordpress.stackexchange.com/users/71675",
"pm_score": 0,
"selected": false,
"text": "<p>For adding JavaScript code in WordPress, you can create a .js file and include it in following way, in your theme's functions.php</p>\n\n<pre><code>/**\n * Proper way to enqueue scripts\n */\nfunction theme_name_scripts() {\n\n wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );\n}\n\nadd_action( 'wp_enqueue_scripts', 'theme_name_scripts' );\n</code></pre>\n\n<p>Refer <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/07/23
|
[
"https://wordpress.stackexchange.com/questions/195335",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68052/"
] |
This is the resulting html I want to produce with a shortcode - when editing page content in WordPress:
```
<div class="shadow-wrapper half-shadow im-centered">
<div class="box-shadow shadow-effect-2">
<div class="servive-block servive-block-bluemed">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nec nulla vitae lacus.
</div>
</div>
</div>
```
This is what I want to use inside of the editor box - when using the new shortcode I will define:
```
[box color="bluemed"]
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nec nulla vitae lacus.
[/box]
```
The parameter being passed: color="bluemed" needs to become part of the div's class.. as in: `<div class="servive-block servive-block-bluemed">` (see above example of resulting html code)
Here is what I have put inside of my functions.php file to try to create this new shortcode:
```
function colored_box_shortcode($atts) {
extract(shortcode_atts(array(
'color' => grey,
), $atts));
return '<div class="shadow-wrapper half-shadow im-centered">
<div class="box-shadow shadow-effect-2">
<div class="servive-block servive-block-'.$color.'">';
}
add_shortcode('box', 'colored_box_shortcode');
function colored_box_end() {
return '</div>
</div>
</div>';
}
add_shortcode('/box', 'colored_box_end');
```
As you can see I set the color attribute default content to be grey, but also allowing the ability to over-ride and specify the color in the parameter that is passed from the shortcode.
This color then needs to become part of the class name inside of the div. So if no parameter is passed then the class name will become: "servive-block-grey". Or if I pass the parameter of color="lavendar", then the class name will become: "servive-block-lavendar".
Is this even possible?
If so.. can someone help with the code I am using.. because I am getting hundreds of errors from WordPress when I view the page.
Basically the errors are a repeat of these 3 (which I think is probably caused by getting a syntax error with me trying to put in the parameter inside of a class name - like this: `servive-block-'.$color.'`)
>
> Warning: preg\_split(): Unknown modifier 'b' in C:\xampp\htdocs\CIRB\CirbWP\wp-includes\formatting.php on line 244
>
>
> Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\CIRB\CirbWP\wp-includes\formatting.php on line 246
>
>
> Warning: implode(): Invalid arguments passed in C:\xampp\htdocs\CIRB\CirbWP\wp-includes\formatting.php on line 297
>
>
>
Thanks for any guidance!
|
You can simply use `require`, `require_once`, `include` or `include_once` functions to include custom PHP files in your theme.
```
require( 'folder/custom.php' );
```
Usually you should keep your custom PHP files in a folder.
Developers [vote against using](https://stackoverflow.com/questions/186338/why-is-require-once-so-bad-to-use) `require_once` because it is a little slower than `require` since it requires the system to keep a log of what's already been included/required.
|
195,353 |
<p>I am using wordpress 4.2.2 and i am using buddypress latest version. I want all my users customize their profile at buddypress profile page. So i want to disable profile.php for the users. I hide the profile link from dashboard by the WP admin UI customize plugin.But when anyone type url mysite/wp-admin/profile.php it's appear on browser.So i want to escape from the problem and want to disable profile.php for the users. What should i do to do this?</p>
|
[
{
"answer_id": 195357,
"author": "Mayeenul Islam",
"author_id": 22728,
"author_profile": "https://wordpress.stackexchange.com/users/22728",
"pm_score": 2,
"selected": false,
"text": "<p>The following code* will redirect non-admin to a custom profile page in the front end, because instead of disabling you need to redirect them to your custom page. :)</p>\n\n<pre><code><?php\nadd_action ('init' , 'wpse_redirect_profile_access');\n\nfunction wpse_redirect_profile_access(){\n //admin won't be affected\n if (current_user_can('manage_options')) return '';\n\n //if we're at admin profile.php page\n if (strpos ($_SERVER ['REQUEST_URI'] , 'wp-admin/profile.php' )) {\n wp_redirect ( home_url( '/my-profile' )); // to page like: example.com/my-profile/\n exit();\n }\n\n}\n</code></pre>\n\n<p>*<a href=\"http://blog.happyplugins.com/redirect-user-profile-page-frontend-page/\" rel=\"nofollow\">Source^</a></p>\n"
},
{
"answer_id": 195370,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<h2>Redirect from <code>profile.php</code> to the dashboard</h2>\n\n<p>Here's one way to do it:</p>\n\n<pre><code>add_action( 'load-profile.php', function() {\n if( ! current_user_can( 'manage_options' ) )\n exit( wp_safe_redirect( admin_url() ) );\n} );\n</code></pre>\n\n<p>where we redirect to the dashboard instead, if the current user can't manage options.</p>\n\n<h2>Redirect from <code>profile.php</code> to the current user's member page</h2>\n\n<p>If you want to redirect to the member's profile page, you could try (untested):</p>\n\n<pre><code>add_action( 'load-profile.php', function() {\n if( ! current_user_can( 'manage_options' ) && function_exists( 'bp_core_get_user_domain' ) )\n exit( wp_safe_redirect( bp_core_get_user_domain( get_current_user_id() ) ) );\n} );\n</code></pre>\n\n<p>The <code>bp_core_get_user_domain()</code> function is mentioned in <a href=\"https://wordpress.stackexchange.com/a/45345/26350\">this answer</a>, few years ago, by @BooneGorges.</p>\n\n<p>I just checked the BP <a href=\"https://buddypress.trac.wordpress.org/browser/branches/2.3/src/bp-members/bp-members-functions.php#L153-192\" rel=\"noreferrer\">source</a> and this function is still available in BP 2.3 (see <a href=\"https://buddypress.trac.wordpress.org/browser/branches/2.3/src/bp-members/bp-members-functions.php#L153-192\" rel=\"noreferrer\">here</a>). </p>\n\n<h2>For PHP < 5.3</h2>\n\n<pre><code>add_action( 'load-profile.php', 'wpse_195353_profile_redirect_to_dashboard' );\nfunction wpse_195353_profile_redirect_to_dashboard()\n{\n if( ! current_user_can( 'manage_options' ) )\n exit( wp_safe_redirect( admin_url() ) );\n}\n</code></pre>\n\n<p>and </p>\n\n<pre><code>add_action( 'load-profile.php', 'wpse_195353_profile_redirect_to_member_page' );\nfunction wpse_195353_profile_redirect_to_member_page()\n{\n if( ! current_user_can( 'manage_options' ) && function_exists( 'bp_core_get_user_domain' ) )\n exit( wp_safe_redirect( bp_core_get_user_domain( get_current_user_id() ) ) );\n}\n</code></pre>\n\n<p>but you should consider updating your PHP if that's the case.</p>\n"
},
{
"answer_id": 195448,
"author": "Bryan Willis",
"author_id": 38123,
"author_profile": "https://wordpress.stackexchange.com/users/38123",
"pm_score": 1,
"selected": false,
"text": "<p>I like this one. You can add admin pages to the array to redirect them. I have it redirecting to the Dashboard below, but you can redirect to BuddyPress URL as well... I'm just not sure what that URL is since I don't use BP very often.</p>\n<pre><code> function no_proflie_admin_pages_redirect() {\n global $pagenow;\n if(!current_user_can('manage_options')) {\n $admin_redirects = array(\n 'profile.php'\n );\n if(in_array($pagenow, $admin_redirects)){\n wp_redirect( admin_url('/') ); exit;\n }\n }\n }\n add_action('admin_init', 'no_proflie_admin_pages_redirect');\n \n</code></pre>\n<p><strong>You can also hide any additional profile.php links with simple CSS:</strong></p>\n<pre><code>function hide_any_profile_links() { ?>\n <style type="text/css">\n a[href="http://example.com/wp-admin/profile.php"], a[href="profile.php"]{\n display: none!important;\n }\n </style>\n<?php }\nadd_action('admin_head', 'hide_any_profile_links', 999);\n</code></pre>\n<p>The above could also be achieved with jquery or using PHP and the output buffer.</p>\n"
},
{
"answer_id": 405131,
"author": "Gerard Reches",
"author_id": 82961,
"author_profile": "https://wordpress.stackexchange.com/users/82961",
"pm_score": 1,
"selected": false,
"text": "<p>Extending on @birgire 's answer, from which I found the first snippet to be the cleanest one I've seen for this, I wanted to add the following since I think it might be useful for most people arriving to this thread.</p>\n<p><strong>If you don't want users to access their profile on the backend, you will most probably also don't want them to be able to access the dashboard.</strong></p>\n<p>The use case is when you have subscribers that you don't want to access the backend at all. By default they can access the dashboard and their profile, so let's avoid that:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function redirect_subscribers () {\n if( ! current_user_can( 'edit_posts' ) ) {\n exit( wp_safe_redirect( site_url() ) );\n }\n}\nadd_action( 'load-index.php', 'redirect_subscribers' );\nadd_action( 'load-profile.php', 'redirect_subscribers' );\n</code></pre>\n<p>Notice that in this case I've used the <code>edit_posts</code> capability, since I'm only targeting subscribers and <a href=\"https://wordpress.org/support/article/roles-and-capabilities/\" rel=\"nofollow noreferrer\">this is a capability all roles have except for subscribers</a>.</p>\n<p>Then I'm using <code>site_url()</code> to redirect them to the homepage, but you could also use <code>get_permalink($page_id)</code> using the <code>id</code> of the page where you have created a "My account" area as a parameter.</p>\n<p>The <code>load-{$page_hook}</code> is <a href=\"https://developer.wordpress.org/reference/hooks/load-page_hook/\" rel=\"nofollow noreferrer\">documented in codex</a>.</p>\n"
}
] |
2015/07/23
|
[
"https://wordpress.stackexchange.com/questions/195353",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75682/"
] |
I am using wordpress 4.2.2 and i am using buddypress latest version. I want all my users customize their profile at buddypress profile page. So i want to disable profile.php for the users. I hide the profile link from dashboard by the WP admin UI customize plugin.But when anyone type url mysite/wp-admin/profile.php it's appear on browser.So i want to escape from the problem and want to disable profile.php for the users. What should i do to do this?
|
Redirect from `profile.php` to the dashboard
--------------------------------------------
Here's one way to do it:
```
add_action( 'load-profile.php', function() {
if( ! current_user_can( 'manage_options' ) )
exit( wp_safe_redirect( admin_url() ) );
} );
```
where we redirect to the dashboard instead, if the current user can't manage options.
Redirect from `profile.php` to the current user's member page
-------------------------------------------------------------
If you want to redirect to the member's profile page, you could try (untested):
```
add_action( 'load-profile.php', function() {
if( ! current_user_can( 'manage_options' ) && function_exists( 'bp_core_get_user_domain' ) )
exit( wp_safe_redirect( bp_core_get_user_domain( get_current_user_id() ) ) );
} );
```
The `bp_core_get_user_domain()` function is mentioned in [this answer](https://wordpress.stackexchange.com/a/45345/26350), few years ago, by @BooneGorges.
I just checked the BP [source](https://buddypress.trac.wordpress.org/browser/branches/2.3/src/bp-members/bp-members-functions.php#L153-192) and this function is still available in BP 2.3 (see [here](https://buddypress.trac.wordpress.org/browser/branches/2.3/src/bp-members/bp-members-functions.php#L153-192)).
For PHP < 5.3
-------------
```
add_action( 'load-profile.php', 'wpse_195353_profile_redirect_to_dashboard' );
function wpse_195353_profile_redirect_to_dashboard()
{
if( ! current_user_can( 'manage_options' ) )
exit( wp_safe_redirect( admin_url() ) );
}
```
and
```
add_action( 'load-profile.php', 'wpse_195353_profile_redirect_to_member_page' );
function wpse_195353_profile_redirect_to_member_page()
{
if( ! current_user_can( 'manage_options' ) && function_exists( 'bp_core_get_user_domain' ) )
exit( wp_safe_redirect( bp_core_get_user_domain( get_current_user_id() ) ) );
}
```
but you should consider updating your PHP if that's the case.
|
195,356 |
<p>I know that WordPress has a faux cron that is called like so when a user visits the page. </p>
<pre><code>register_activation_hook(__FILE__, 'my_activation');
add_action('my_hourly_event', 'do_this_hourly');
function my_activation() {
wp_schedule_event(time(), 'hourly', 'my_hourly_event');
}
function do_this_hourly() {
// do something every hour
}
</code></pre>
<p>I want to use linux cron like so: </p>
<pre><code>*/5 * * * * * /usr/local/bin/php/ /Path/to/file
</code></pre>
<p>The problem is that if that file is like this: </p>
<pre><code><?php
function do_something() {
echo 'Hello World';
}
do_something();
</code></pre>
<p>Do something function is called every time I reload the page. What I need is a way to specify with linux cron so that do_something() is only called when it is time to run cron. So the file should just have the function definition of do_something() it shouldn't call the function directly. </p>
<pre><code><?php
function do_something() {
echo 'Hello World';
}
</code></pre>
|
[
{
"answer_id": 195357,
"author": "Mayeenul Islam",
"author_id": 22728,
"author_profile": "https://wordpress.stackexchange.com/users/22728",
"pm_score": 2,
"selected": false,
"text": "<p>The following code* will redirect non-admin to a custom profile page in the front end, because instead of disabling you need to redirect them to your custom page. :)</p>\n\n<pre><code><?php\nadd_action ('init' , 'wpse_redirect_profile_access');\n\nfunction wpse_redirect_profile_access(){\n //admin won't be affected\n if (current_user_can('manage_options')) return '';\n\n //if we're at admin profile.php page\n if (strpos ($_SERVER ['REQUEST_URI'] , 'wp-admin/profile.php' )) {\n wp_redirect ( home_url( '/my-profile' )); // to page like: example.com/my-profile/\n exit();\n }\n\n}\n</code></pre>\n\n<p>*<a href=\"http://blog.happyplugins.com/redirect-user-profile-page-frontend-page/\" rel=\"nofollow\">Source^</a></p>\n"
},
{
"answer_id": 195370,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<h2>Redirect from <code>profile.php</code> to the dashboard</h2>\n\n<p>Here's one way to do it:</p>\n\n<pre><code>add_action( 'load-profile.php', function() {\n if( ! current_user_can( 'manage_options' ) )\n exit( wp_safe_redirect( admin_url() ) );\n} );\n</code></pre>\n\n<p>where we redirect to the dashboard instead, if the current user can't manage options.</p>\n\n<h2>Redirect from <code>profile.php</code> to the current user's member page</h2>\n\n<p>If you want to redirect to the member's profile page, you could try (untested):</p>\n\n<pre><code>add_action( 'load-profile.php', function() {\n if( ! current_user_can( 'manage_options' ) && function_exists( 'bp_core_get_user_domain' ) )\n exit( wp_safe_redirect( bp_core_get_user_domain( get_current_user_id() ) ) );\n} );\n</code></pre>\n\n<p>The <code>bp_core_get_user_domain()</code> function is mentioned in <a href=\"https://wordpress.stackexchange.com/a/45345/26350\">this answer</a>, few years ago, by @BooneGorges.</p>\n\n<p>I just checked the BP <a href=\"https://buddypress.trac.wordpress.org/browser/branches/2.3/src/bp-members/bp-members-functions.php#L153-192\" rel=\"noreferrer\">source</a> and this function is still available in BP 2.3 (see <a href=\"https://buddypress.trac.wordpress.org/browser/branches/2.3/src/bp-members/bp-members-functions.php#L153-192\" rel=\"noreferrer\">here</a>). </p>\n\n<h2>For PHP < 5.3</h2>\n\n<pre><code>add_action( 'load-profile.php', 'wpse_195353_profile_redirect_to_dashboard' );\nfunction wpse_195353_profile_redirect_to_dashboard()\n{\n if( ! current_user_can( 'manage_options' ) )\n exit( wp_safe_redirect( admin_url() ) );\n}\n</code></pre>\n\n<p>and </p>\n\n<pre><code>add_action( 'load-profile.php', 'wpse_195353_profile_redirect_to_member_page' );\nfunction wpse_195353_profile_redirect_to_member_page()\n{\n if( ! current_user_can( 'manage_options' ) && function_exists( 'bp_core_get_user_domain' ) )\n exit( wp_safe_redirect( bp_core_get_user_domain( get_current_user_id() ) ) );\n}\n</code></pre>\n\n<p>but you should consider updating your PHP if that's the case.</p>\n"
},
{
"answer_id": 195448,
"author": "Bryan Willis",
"author_id": 38123,
"author_profile": "https://wordpress.stackexchange.com/users/38123",
"pm_score": 1,
"selected": false,
"text": "<p>I like this one. You can add admin pages to the array to redirect them. I have it redirecting to the Dashboard below, but you can redirect to BuddyPress URL as well... I'm just not sure what that URL is since I don't use BP very often.</p>\n<pre><code> function no_proflie_admin_pages_redirect() {\n global $pagenow;\n if(!current_user_can('manage_options')) {\n $admin_redirects = array(\n 'profile.php'\n );\n if(in_array($pagenow, $admin_redirects)){\n wp_redirect( admin_url('/') ); exit;\n }\n }\n }\n add_action('admin_init', 'no_proflie_admin_pages_redirect');\n \n</code></pre>\n<p><strong>You can also hide any additional profile.php links with simple CSS:</strong></p>\n<pre><code>function hide_any_profile_links() { ?>\n <style type="text/css">\n a[href="http://example.com/wp-admin/profile.php"], a[href="profile.php"]{\n display: none!important;\n }\n </style>\n<?php }\nadd_action('admin_head', 'hide_any_profile_links', 999);\n</code></pre>\n<p>The above could also be achieved with jquery or using PHP and the output buffer.</p>\n"
},
{
"answer_id": 405131,
"author": "Gerard Reches",
"author_id": 82961,
"author_profile": "https://wordpress.stackexchange.com/users/82961",
"pm_score": 1,
"selected": false,
"text": "<p>Extending on @birgire 's answer, from which I found the first snippet to be the cleanest one I've seen for this, I wanted to add the following since I think it might be useful for most people arriving to this thread.</p>\n<p><strong>If you don't want users to access their profile on the backend, you will most probably also don't want them to be able to access the dashboard.</strong></p>\n<p>The use case is when you have subscribers that you don't want to access the backend at all. By default they can access the dashboard and their profile, so let's avoid that:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function redirect_subscribers () {\n if( ! current_user_can( 'edit_posts' ) ) {\n exit( wp_safe_redirect( site_url() ) );\n }\n}\nadd_action( 'load-index.php', 'redirect_subscribers' );\nadd_action( 'load-profile.php', 'redirect_subscribers' );\n</code></pre>\n<p>Notice that in this case I've used the <code>edit_posts</code> capability, since I'm only targeting subscribers and <a href=\"https://wordpress.org/support/article/roles-and-capabilities/\" rel=\"nofollow noreferrer\">this is a capability all roles have except for subscribers</a>.</p>\n<p>Then I'm using <code>site_url()</code> to redirect them to the homepage, but you could also use <code>get_permalink($page_id)</code> using the <code>id</code> of the page where you have created a "My account" area as a parameter.</p>\n<p>The <code>load-{$page_hook}</code> is <a href=\"https://developer.wordpress.org/reference/hooks/load-page_hook/\" rel=\"nofollow noreferrer\">documented in codex</a>.</p>\n"
}
] |
2015/07/23
|
[
"https://wordpress.stackexchange.com/questions/195356",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48204/"
] |
I know that WordPress has a faux cron that is called like so when a user visits the page.
```
register_activation_hook(__FILE__, 'my_activation');
add_action('my_hourly_event', 'do_this_hourly');
function my_activation() {
wp_schedule_event(time(), 'hourly', 'my_hourly_event');
}
function do_this_hourly() {
// do something every hour
}
```
I want to use linux cron like so:
```
*/5 * * * * * /usr/local/bin/php/ /Path/to/file
```
The problem is that if that file is like this:
```
<?php
function do_something() {
echo 'Hello World';
}
do_something();
```
Do something function is called every time I reload the page. What I need is a way to specify with linux cron so that do\_something() is only called when it is time to run cron. So the file should just have the function definition of do\_something() it shouldn't call the function directly.
```
<?php
function do_something() {
echo 'Hello World';
}
```
|
Redirect from `profile.php` to the dashboard
--------------------------------------------
Here's one way to do it:
```
add_action( 'load-profile.php', function() {
if( ! current_user_can( 'manage_options' ) )
exit( wp_safe_redirect( admin_url() ) );
} );
```
where we redirect to the dashboard instead, if the current user can't manage options.
Redirect from `profile.php` to the current user's member page
-------------------------------------------------------------
If you want to redirect to the member's profile page, you could try (untested):
```
add_action( 'load-profile.php', function() {
if( ! current_user_can( 'manage_options' ) && function_exists( 'bp_core_get_user_domain' ) )
exit( wp_safe_redirect( bp_core_get_user_domain( get_current_user_id() ) ) );
} );
```
The `bp_core_get_user_domain()` function is mentioned in [this answer](https://wordpress.stackexchange.com/a/45345/26350), few years ago, by @BooneGorges.
I just checked the BP [source](https://buddypress.trac.wordpress.org/browser/branches/2.3/src/bp-members/bp-members-functions.php#L153-192) and this function is still available in BP 2.3 (see [here](https://buddypress.trac.wordpress.org/browser/branches/2.3/src/bp-members/bp-members-functions.php#L153-192)).
For PHP < 5.3
-------------
```
add_action( 'load-profile.php', 'wpse_195353_profile_redirect_to_dashboard' );
function wpse_195353_profile_redirect_to_dashboard()
{
if( ! current_user_can( 'manage_options' ) )
exit( wp_safe_redirect( admin_url() ) );
}
```
and
```
add_action( 'load-profile.php', 'wpse_195353_profile_redirect_to_member_page' );
function wpse_195353_profile_redirect_to_member_page()
{
if( ! current_user_can( 'manage_options' ) && function_exists( 'bp_core_get_user_domain' ) )
exit( wp_safe_redirect( bp_core_get_user_domain( get_current_user_id() ) ) );
}
```
but you should consider updating your PHP if that's the case.
|
195,362 |
<p>I've got a realy hair pulling problem here.</p>
<p>I've started cleaning up a plugin i've made and sort some of the functions in diffrent files.</p>
<p>but i've got a problem with wp_enqueue_scripts.</p>
<p>when i place the function where i register and enqueue in the main php file and try to enqueue my script from there it works as it should</p>
<p>however if i move the function to a diffrent php file and try to enqueue it from that file
and include this php file from the main php file
nothing happens however all other funtions from this php file works as they should</p>
<p>do i need to call a wordpress function from my other php file to be able to unqueue it from there or?</p>
<p>EDIT: </p>
<p>If if place and call the function in my main php file like below it works like a charm
and and the js file is shown in the head when i look for it with firefox</p>
<pre><code>function scripts() {
wp_register_script( 'load_table', plugins_url( 'path/js/load_table.js', __FILE__ ), array( 'jquery' ) );
wp_enqueue_script( 'load_table' );
}
add_action( 'wp_enqueue_scripts', 'scripts' );
</code></pre>
<p>However if i try to write it like below nothing happens and it cant be found in the head either</p>
<p>main.php:</p>
<pre><code>include'path/to/other.php';
</code></pre>
<p>other.php:</p>
<pre><code>function scripts() {
wp_register_script( 'load_table', plugins_url( 'vagt_oversigt/js/load_table.js', __FILE__ ), array( 'jquery' ) );
wp_enqueue_script( 'load_table' );
}
add_action( 'wp_enqueue_scripts', 'scripts' );
</code></pre>
<p>The problems seems to be happening when i use hooks with functions on other.php</p>
<p>just <code>echo "hello world";</code> in other.php it works like a charm.</p>
<p>But if i try calling echo with in a function by init nothing happens either.</p>
<p>other.php:</p>
<pre><code>function test() {
echo "hello world";
}
add_action('init', 'test');
</code></pre>
<p>BTW! yes i did try changing the path without sucsess. any ideas? :(</p>
|
[
{
"answer_id": 195380,
"author": "Harry",
"author_id": 76642,
"author_profile": "https://wordpress.stackexchange.com/users/76642",
"pm_score": 0,
"selected": false,
"text": "<p>You have to place the enqueue code with in a function and use add_action to call the function where you register.</p>\n\n<p>Like below</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'your_function_name', 10 );\n</code></pre>\n"
},
{
"answer_id": 195395,
"author": "Alexander",
"author_id": 69346,
"author_profile": "https://wordpress.stackexchange.com/users/69346",
"pm_score": 1,
"selected": false,
"text": "<p>I found the problem....</p>\n\n<p>I ran main.php like:</p>\n\n<pre><code>function run_this(){\n\ninclude'path/to/other.php';\n}\nadd_shortcode('shortcode', 'run_this');\n</code></pre>\n\n<p>And most of the content of other.php came up exept the hooks did'nt work\nthen i tried using <code>add_action('init', 'run_this');</code> and then it worked....\nexept that i get a fatal error that i cant redeclare some functions twice :D</p>\n"
}
] |
2015/07/23
|
[
"https://wordpress.stackexchange.com/questions/195362",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69346/"
] |
I've got a realy hair pulling problem here.
I've started cleaning up a plugin i've made and sort some of the functions in diffrent files.
but i've got a problem with wp\_enqueue\_scripts.
when i place the function where i register and enqueue in the main php file and try to enqueue my script from there it works as it should
however if i move the function to a diffrent php file and try to enqueue it from that file
and include this php file from the main php file
nothing happens however all other funtions from this php file works as they should
do i need to call a wordpress function from my other php file to be able to unqueue it from there or?
EDIT:
If if place and call the function in my main php file like below it works like a charm
and and the js file is shown in the head when i look for it with firefox
```
function scripts() {
wp_register_script( 'load_table', plugins_url( 'path/js/load_table.js', __FILE__ ), array( 'jquery' ) );
wp_enqueue_script( 'load_table' );
}
add_action( 'wp_enqueue_scripts', 'scripts' );
```
However if i try to write it like below nothing happens and it cant be found in the head either
main.php:
```
include'path/to/other.php';
```
other.php:
```
function scripts() {
wp_register_script( 'load_table', plugins_url( 'vagt_oversigt/js/load_table.js', __FILE__ ), array( 'jquery' ) );
wp_enqueue_script( 'load_table' );
}
add_action( 'wp_enqueue_scripts', 'scripts' );
```
The problems seems to be happening when i use hooks with functions on other.php
just `echo "hello world";` in other.php it works like a charm.
But if i try calling echo with in a function by init nothing happens either.
other.php:
```
function test() {
echo "hello world";
}
add_action('init', 'test');
```
BTW! yes i did try changing the path without sucsess. any ideas? :(
|
I found the problem....
I ran main.php like:
```
function run_this(){
include'path/to/other.php';
}
add_shortcode('shortcode', 'run_this');
```
And most of the content of other.php came up exept the hooks did'nt work
then i tried using `add_action('init', 'run_this');` and then it worked....
exept that i get a fatal error that i cant redeclare some functions twice :D
|
195,377 |
<p>With the release of Chrome Version 44.0.2403.89 m, I've noticed that our site is now completely broken. All of the HTTP URLs are being redirected to HTTPS URLs, which is a problem because our site does <strong>not</strong> support HTTPS. </p>
<p>Please note, this is not happening in any other browser, and was working on the previous Chrome release.</p>
<p>I've tried to replace all of our stylesheet calls with relative links, and that has worked, but the images that are loaded in automatically or through absolute paths as well as the navigation is still broken. Please see below image for the error page that is thrown when navigating, after accepting the security warning and proceeding.</p>
<p><a href="https://i.stack.imgur.com/vpPXH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vpPXH.png" alt="Error thrown when navigating to a page."></a></p>
<p>Anyone have any advice as far as updating perhaps the .htaccess file goes, or something in functions?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 195397,
"author": "Stepan",
"author_id": 76656,
"author_profile": "https://wordpress.stackexchange.com/users/76656",
"pm_score": 4,
"selected": true,
"text": "<p><strong>Solution 1:</strong> \nEnable mod_header on the server and added this rule to my appache2.conf file:</p>\n\n<pre><code><IfModule mod_headers.c>\n RequestHeader unset HTTPS\n</IfModule>\n</code></pre>\n\n<p><strong>Solution 2:</strong>\nOr you need to add the code to fonction.php file of your current theme:</p>\n\n<pre><code>function https_chrome44fix() {\n $_SERVER['HTTPS'] = false;\n}\nadd_action('init', 'https_chrome44fix',0); \n</code></pre>\n"
},
{
"answer_id": 195398,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 3,
"selected": false,
"text": "<p>This seems to be a bug that affects only Apache which is sending the <em>user value</em> for the header <code>HTTPS</code> as unprefixed header <code>HTTPS</code> instead of <code>HTTP_HTTPS</code>.</p>\n\n<p>You should be able to fix that with a <a href=\"https://gist.github.com/toscho/e0ea08040d16dd671201\" rel=\"nofollow\">simple plugin</a>:</p>\n\n<pre><code>if ( empty ( $_SERVER['SERVER_SOFTWARE'] ) )\n return;\n\nif ( FALSE === stristr( $_SERVER['SERVER_SOFTWARE'], 'apache' ) )\n return;\n\nif ( empty ( $_SERVER['HTTPS'] ) )\n return;\n\nif ( '1' === $_SERVER['HTTPS'] )\n $_SERVER['HTTPS'] = FALSE;\n\nif ( '1' === $_SERVER['HTTP_HTTPS'] )\n $_SERVER['HTTP_HTTPS'] = FALSE;\n</code></pre>\n"
},
{
"answer_id": 195404,
"author": "Stefano",
"author_id": 76661,
"author_profile": "https://wordpress.stackexchange.com/users/76661",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is the last update of google chrome.</p>\n\n<p>You can use this to resolve until the <a href=\"https://github.com/IshYoBoy/aaa-ishyoboy-google-chrome-44-ssl-fix\" rel=\"nofollow\">new release of chrome</a></p>\n\n<p>See also <a href=\"https://code.google.com/p/chromium/issues/detail?id=505268\" rel=\"nofollow\">this page</a> for more info</p>\n"
},
{
"answer_id": 195445,
"author": "Jigar Kotak",
"author_id": 76688,
"author_profile": "https://wordpress.stackexchange.com/users/76688",
"pm_score": -1,
"selected": false,
"text": "<p>You need to add the code to fonction.php file of your current theme:</p>\n\n<pre><code>if (!is_ssl()) {\n $_SERVER['HTTPS'] = false;\n}\n</code></pre>\n"
},
{
"answer_id": 195447,
"author": "Jukka Rautanen",
"author_id": 76689,
"author_profile": "https://wordpress.stackexchange.com/users/76689",
"pm_score": 2,
"selected": false,
"text": "<p>WooCommerce has released an update fixing this problem (at least for me)</p>\n\n<p><em>Fix - Fixed Google Chrome forcing to use SSL. This can cause some issues on websites behind load balancers or reverse proxies. Read more.</em></p>\n\n<p>Detailed notes at <a href=\"http://develop.woothemes.com/woocommerce/2015/07/woocommerce-2-3-13-security-and-maintenance-release/\" rel=\"nofollow\">their blog post</a> or in <a href=\"https://github.com/woothemes/woocommerce/issues/8479\" rel=\"nofollow\">GitHub</a>.</p>\n\n<p>Make sure to refresh your caching plugins after updating, if you are using one.</p>\n"
}
] |
2015/07/23
|
[
"https://wordpress.stackexchange.com/questions/195377",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64518/"
] |
With the release of Chrome Version 44.0.2403.89 m, I've noticed that our site is now completely broken. All of the HTTP URLs are being redirected to HTTPS URLs, which is a problem because our site does **not** support HTTPS.
Please note, this is not happening in any other browser, and was working on the previous Chrome release.
I've tried to replace all of our stylesheet calls with relative links, and that has worked, but the images that are loaded in automatically or through absolute paths as well as the navigation is still broken. Please see below image for the error page that is thrown when navigating, after accepting the security warning and proceeding.
[](https://i.stack.imgur.com/vpPXH.png)
Anyone have any advice as far as updating perhaps the .htaccess file goes, or something in functions?
Thanks.
|
**Solution 1:**
Enable mod\_header on the server and added this rule to my appache2.conf file:
```
<IfModule mod_headers.c>
RequestHeader unset HTTPS
</IfModule>
```
**Solution 2:**
Or you need to add the code to fonction.php file of your current theme:
```
function https_chrome44fix() {
$_SERVER['HTTPS'] = false;
}
add_action('init', 'https_chrome44fix',0);
```
|
195,425 |
<p>I would like to display 6 featured products from my woocommerce store on my home-page.php template. After some researched I found that the right way to do this was through a custom loop,( I do not wish to use shortcodes because I would like to add additional classes for styling etc. ) I also found that the key that woocommerce uses for the featured products is '_featured'. I put together the code below to display any products that I chose to be featured products in my store, but it doesn't work... Any help is appreciated.</p>
<pre><code><?php
$args = array(
'post_type' => 'product',
'stock' => 1,
'showposts' => 6,
'orderby' => 'date',
'order' => 'DESC' ,
'meta_query' => array(
array(
'key' => '_featured',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
)
)
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
<li>
<?php
if ( has_post_thumbnail( $loop->post->ID ) )
echo get_the_post_thumbnail( $loop->post->ID, 'shop_catalog' );
else
echo '<img src="' . woocommerce_placeholder_img_src() . '" alt="Placeholder" width="65px" height="115px" />';
?>
<h3><?php the_title(); ?></h3>
<?php
echo $product->get_price_html();
woocommerce_template_loop_add_to_cart( $loop->post, $product );
?>
</li>
<?php
endwhile;
wp_reset_query();
?>
</code></pre>
|
[
{
"answer_id": 202739,
"author": "Hooman Askari",
"author_id": 31189,
"author_profile": "https://wordpress.stackexchange.com/users/31189",
"pm_score": 5,
"selected": true,
"text": "<p>Change your args to be like this:</p>\n\n<pre><code>$meta_query = WC()->query->get_meta_query();\n$meta_query[] = array(\n 'key' => '_featured',\n 'value' => 'yes'\n);\n$args = array(\n 'post_type' => 'product',\n 'stock' => 1,\n 'showposts' => 6,\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'meta_query' => $meta_query\n);\n</code></pre>\n\n<p>If you go to wp-content/plugins/woocommerce/includes/class-wc-shortcodes.php (@595) you can find how it's done for WC shortcodes.</p>\n"
},
{
"answer_id": 232010,
"author": "Aamer Shahzad",
"author_id": 42772,
"author_profile": "https://wordpress.stackexchange.com/users/42772",
"pm_score": 0,
"selected": false,
"text": "<p>if you take a look in the database in <code>wp_postmeta</code> table you will see <code>meta_key</code> will be <code>_featured</code> and <code>meta_value</code> will be <code>yes</code> or <code>no</code> so instead of value <code>0</code> or <code>1</code> write <code>yes</code> or <code>no</code> </p>\n\n<pre><code><?php\n $q = new WP_Query([\n 'post_type' => 'product',\n 'stock' => 1,\n 'showposts' => 3,\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'meta_query' => [ \n ['key' => '_featured', 'value' => 'yes' ]\n ]\n ]);\n if ( $q->have_posts() ) :\n while ( $q->have_posts() ) : $q->the_post();\n // display product info\n endwhile; wp_reset_query();\n endif;\n?>\n</code></pre>\n"
},
{
"answer_id": 266252,
"author": "dpruth",
"author_id": 78022,
"author_profile": "https://wordpress.stackexchange.com/users/78022",
"pm_score": 5,
"selected": false,
"text": "<p>This has changed in WooCommerce 3.0. It's not simply a meta_query, but now includes a tax_query. The arguments are now:</p>\n\n<pre><code> $meta_query = WC()->query->get_meta_query();\n $tax_query = WC()->query->get_tax_query();\n $tax_query[] = array(\n 'taxonomy' => 'product_visibility',\n 'field' => 'name',\n 'terms' => 'featured',\n 'operator' => 'IN',\n );\n\n $args = array(\n 'post_type' => 'product',\n 'post_status' => 'publish',\n 'ignore_sticky_posts' => 1,\n 'posts_per_page' => $atts['per_page'],\n 'orderby' => $atts['orderby'],\n 'order' => $atts['order'],\n 'meta_query' => $meta_query,\n 'tax_query' => $tax_query,\n );\n</code></pre>\n\n<p>See woocommerce/includes/class-wc-shortcodes.php</p>\n"
},
{
"answer_id": 289382,
"author": "Mostafa Norzade",
"author_id": 131388,
"author_profile": "https://wordpress.stackexchange.com/users/131388",
"pm_score": 3,
"selected": false,
"text": "<p>Featured Products Loop in WooCommerce 3</p>\n\n<pre><code><ul class=\"products\">\n<?php\n$args = array(\n 'post_type' => 'product',\n 'posts_per_page' => 12,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'product_visibility',\n 'field' => 'name',\n 'terms' => 'featured',\n ),\n ),\n );\n$loop = new WP_Query( $args );\nif ( $loop->have_posts() ) {\n while ( $loop->have_posts() ) : $loop->the_post();\n wc_get_template_part( 'content', 'product' );\n endwhile;\n} else {\n echo __( 'No products found' );\n}\nwp_reset_postdata();\n?>\n</code></pre>\n"
},
{
"answer_id": 302194,
"author": "Felipe Elia",
"author_id": 122788,
"author_profile": "https://wordpress.stackexchange.com/users/122788",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is quite old, but I've just shared an alternative solution <a href=\"https://stackoverflow.com/a/50081494/5970334\">here</a> and I think it can help those reaching this topic too.</p>\n\n<p>Instead of using <code>meta_query</code> or <code>tax_query</code>, you can use <a href=\"https://docs.woocommerce.com/wc-apidocs/function-wc_get_featured_product_ids.html\" rel=\"nofollow noreferrer\">wc_get_featured_product_ids()</a> too:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'product',\n 'posts_per_page' => 6,\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'post__in' => wc_get_featured_product_ids(),\n);\n\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>I hope it helps!</p>\n"
},
{
"answer_id": 304374,
"author": "cfx",
"author_id": 28957,
"author_profile": "https://wordpress.stackexchange.com/users/28957",
"pm_score": 3,
"selected": false,
"text": "<p>According to the <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query\" rel=\"noreferrer\">WooCommerce Wiki</a>:</p>\n\n<blockquote>\n <p><strong>Building custom WP_Queries or database queries [to retrieve products] is likely to break your code</strong> in future versions of WooCommerce as data moves towards custom tables for better performance.</p>\n</blockquote>\n\n<p>WooCommerce advocates using <code>wc_get_products()</code> or <code>WC_Product_Query()</code> instead of <code>WP_Query()</code> or <code>get_posts()</code>.</p>\n\n<p>I've written a post with the code I used to achieve what you want here: <a href=\"https://cfxdesign.com/create-a-custom-woocommerce-product-loop-the-right-way/\" rel=\"noreferrer\">https://cfxdesign.com/create-a-custom-woocommerce-product-loop-the-right-way/</a></p>\n"
},
{
"answer_id": 315190,
"author": "conschneider",
"author_id": 108696,
"author_profile": "https://wordpress.stackexchange.com/users/108696",
"pm_score": 1,
"selected": false,
"text": "<p>Based on: <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query\" rel=\"nofollow noreferrer\">https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query</a></p>\n\n<p>I would try: </p>\n\n<p>outside loop: </p>\n\n<pre><code>$args = array (\n'limit' => 6,\n'orderby' => 'title',\n'order' => 'ASC',\n'category' => $club_cat,\n'stock_status' => 'instock',\n'featured' => true,\n\n );\n\n $products = wc_get_products( $args );\n</code></pre>\n\n<p>in the loop: </p>\n\n<pre><code>$query = new WC_Product_Query( array(\n'limit' => 6,\n'orderby' => 'title',\n'order' => 'ASC',\n'category' => $club_cat,\n'stock_status' => 'instock',\n'featured' => true,\n'return' => 'ids',\n\n ) );\n\n $products = $query->get_products();\n</code></pre>\n"
},
{
"answer_id": 333357,
"author": "Dhaval",
"author_id": 164378,
"author_profile": "https://wordpress.stackexchange.com/users/164378",
"pm_score": 0,
"selected": false,
"text": "<pre><code><ul class=\"products\">\n <?php\n $args = array(\n 'post_type' => 'product',\n 'posts_per_page' => 12,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'product_visibility',\n 'field' => 'name',\n 'terms' => 'featured',\n ),\n ),\n );\n $loop = new WP_Query( $args );\n if ( $loop->have_posts() ) {\n while ( $loop->have_posts() ) : $loop->the_post();\n echo '<p>'.get_the_title().'</p>';\n endwhile;\n } else {\n echo __( 'No products found' );\n }\n wp_reset_postdata();\n ?>\n</ul><!--/.products-->\n</code></pre>\n"
},
{
"answer_id": 370913,
"author": "jameshwart lopez",
"author_id": 75608,
"author_profile": "https://wordpress.stackexchange.com/users/75608",
"pm_score": 1,
"selected": false,
"text": "<p>People should start using wc_get_products because woocommerce said this is the standard way of retrieving product. wc_get_products has an argument featured which just needs to be set to true. So the code is simply below.</p>\n<pre><code> <?php \n\n// Display featured products by category. on this case its "shirts" which is the slug of the category.\n$query_args = array(\n 'featured' => true, \n 'category' => array( 'shirts' ),\n);\n$products = wc_get_products( $query_args );\n\nglobal $post;\n$columns = wc_get_loop_prop( 'columns' );\n?>\n<div class="woocommerce columns-<?php echo esc_attr( $columns ); ?>">\n <?php\n woocommerce_product_loop_start();\n foreach ($products as $product) {\n $post = get_post($product->get_id());\n setup_postdata($post);\n wc_get_template_part('content', 'product');\n }\n wp_reset_postdata();\n woocommerce_product_loop_end();\n ?>\n</div>\n</code></pre>\n<p>See full post here: <a href=\"https://jameshwartlopez.com/plugin/get-featured-products-of-a-category/\" rel=\"nofollow noreferrer\">https://jameshwartlopez.com/plugin/get-featured-products-of-a-category/</a></p>\n"
},
{
"answer_id": 392894,
"author": "Chad Reitsma",
"author_id": 160601,
"author_profile": "https://wordpress.stackexchange.com/users/160601",
"pm_score": 0,
"selected": false,
"text": "<p>Bump for 2021 - You need to be using <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query\" rel=\"nofollow noreferrer\">wc_get_products()</a></p>\n<p>Also, the code example from Jameshwart (above) didn't work for me, this is how I set up the postdata & use wc_get_template. Tested & working.</p>\n<pre><code>$args = array(\n 'status' => 'publish',\n 'limit' => 20,\n 'paginate' => true, //must be true in order to get ->total\n 'return' => 'ids',\n);\n$products = wc_get_products( $args );\n\nif ($products->total >= 1):\n\n woocommerce_product_loop_start();\n\n foreach($products->products as $pid):\n\n do_action( 'woocommerce_shop_loop' );\n\n $product = get_post($pid);\n setup_postdata($GLOBALS['post'] =& $product);\n wc_get_template_part('content', 'product');\n\n endforeach;\n wp_reset_postdata();\n\n woocommerce_product_loop_end();\n\n\nendif; //we have products\n</code></pre>\n"
}
] |
2015/07/23
|
[
"https://wordpress.stackexchange.com/questions/195425",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67512/"
] |
I would like to display 6 featured products from my woocommerce store on my home-page.php template. After some researched I found that the right way to do this was through a custom loop,( I do not wish to use shortcodes because I would like to add additional classes for styling etc. ) I also found that the key that woocommerce uses for the featured products is '\_featured'. I put together the code below to display any products that I chose to be featured products in my store, but it doesn't work... Any help is appreciated.
```
<?php
$args = array(
'post_type' => 'product',
'stock' => 1,
'showposts' => 6,
'orderby' => 'date',
'order' => 'DESC' ,
'meta_query' => array(
array(
'key' => '_featured',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
)
)
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
<li>
<?php
if ( has_post_thumbnail( $loop->post->ID ) )
echo get_the_post_thumbnail( $loop->post->ID, 'shop_catalog' );
else
echo '<img src="' . woocommerce_placeholder_img_src() . '" alt="Placeholder" width="65px" height="115px" />';
?>
<h3><?php the_title(); ?></h3>
<?php
echo $product->get_price_html();
woocommerce_template_loop_add_to_cart( $loop->post, $product );
?>
</li>
<?php
endwhile;
wp_reset_query();
?>
```
|
Change your args to be like this:
```
$meta_query = WC()->query->get_meta_query();
$meta_query[] = array(
'key' => '_featured',
'value' => 'yes'
);
$args = array(
'post_type' => 'product',
'stock' => 1,
'showposts' => 6,
'orderby' => 'date',
'order' => 'DESC',
'meta_query' => $meta_query
);
```
If you go to wp-content/plugins/woocommerce/includes/class-wc-shortcodes.php (@595) you can find how it's done for WC shortcodes.
|
195,434 |
<p>I want to update my old website with WordPress but I got some problems...
Is it possible to create a website without domain name (before publish) and replace it with my old website domain name as soon as i finish building the new one?
Basically, I want to keep my old website (not built by WordPress) while I am working on the new web. Then use the domain name that I have for the old web to replace it with the new web that I will build in WordPress.</p>
<p>First I start building a new "free WordPress.com" but it's not in admin site, so i ran into lots of difficulties when I used it. So i want to start over and do it on admin site but I got problem with the domain now :(</p>
<p>Thank you! </p>
|
[
{
"answer_id": 202739,
"author": "Hooman Askari",
"author_id": 31189,
"author_profile": "https://wordpress.stackexchange.com/users/31189",
"pm_score": 5,
"selected": true,
"text": "<p>Change your args to be like this:</p>\n\n<pre><code>$meta_query = WC()->query->get_meta_query();\n$meta_query[] = array(\n 'key' => '_featured',\n 'value' => 'yes'\n);\n$args = array(\n 'post_type' => 'product',\n 'stock' => 1,\n 'showposts' => 6,\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'meta_query' => $meta_query\n);\n</code></pre>\n\n<p>If you go to wp-content/plugins/woocommerce/includes/class-wc-shortcodes.php (@595) you can find how it's done for WC shortcodes.</p>\n"
},
{
"answer_id": 232010,
"author": "Aamer Shahzad",
"author_id": 42772,
"author_profile": "https://wordpress.stackexchange.com/users/42772",
"pm_score": 0,
"selected": false,
"text": "<p>if you take a look in the database in <code>wp_postmeta</code> table you will see <code>meta_key</code> will be <code>_featured</code> and <code>meta_value</code> will be <code>yes</code> or <code>no</code> so instead of value <code>0</code> or <code>1</code> write <code>yes</code> or <code>no</code> </p>\n\n<pre><code><?php\n $q = new WP_Query([\n 'post_type' => 'product',\n 'stock' => 1,\n 'showposts' => 3,\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'meta_query' => [ \n ['key' => '_featured', 'value' => 'yes' ]\n ]\n ]);\n if ( $q->have_posts() ) :\n while ( $q->have_posts() ) : $q->the_post();\n // display product info\n endwhile; wp_reset_query();\n endif;\n?>\n</code></pre>\n"
},
{
"answer_id": 266252,
"author": "dpruth",
"author_id": 78022,
"author_profile": "https://wordpress.stackexchange.com/users/78022",
"pm_score": 5,
"selected": false,
"text": "<p>This has changed in WooCommerce 3.0. It's not simply a meta_query, but now includes a tax_query. The arguments are now:</p>\n\n<pre><code> $meta_query = WC()->query->get_meta_query();\n $tax_query = WC()->query->get_tax_query();\n $tax_query[] = array(\n 'taxonomy' => 'product_visibility',\n 'field' => 'name',\n 'terms' => 'featured',\n 'operator' => 'IN',\n );\n\n $args = array(\n 'post_type' => 'product',\n 'post_status' => 'publish',\n 'ignore_sticky_posts' => 1,\n 'posts_per_page' => $atts['per_page'],\n 'orderby' => $atts['orderby'],\n 'order' => $atts['order'],\n 'meta_query' => $meta_query,\n 'tax_query' => $tax_query,\n );\n</code></pre>\n\n<p>See woocommerce/includes/class-wc-shortcodes.php</p>\n"
},
{
"answer_id": 289382,
"author": "Mostafa Norzade",
"author_id": 131388,
"author_profile": "https://wordpress.stackexchange.com/users/131388",
"pm_score": 3,
"selected": false,
"text": "<p>Featured Products Loop in WooCommerce 3</p>\n\n<pre><code><ul class=\"products\">\n<?php\n$args = array(\n 'post_type' => 'product',\n 'posts_per_page' => 12,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'product_visibility',\n 'field' => 'name',\n 'terms' => 'featured',\n ),\n ),\n );\n$loop = new WP_Query( $args );\nif ( $loop->have_posts() ) {\n while ( $loop->have_posts() ) : $loop->the_post();\n wc_get_template_part( 'content', 'product' );\n endwhile;\n} else {\n echo __( 'No products found' );\n}\nwp_reset_postdata();\n?>\n</code></pre>\n"
},
{
"answer_id": 302194,
"author": "Felipe Elia",
"author_id": 122788,
"author_profile": "https://wordpress.stackexchange.com/users/122788",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is quite old, but I've just shared an alternative solution <a href=\"https://stackoverflow.com/a/50081494/5970334\">here</a> and I think it can help those reaching this topic too.</p>\n\n<p>Instead of using <code>meta_query</code> or <code>tax_query</code>, you can use <a href=\"https://docs.woocommerce.com/wc-apidocs/function-wc_get_featured_product_ids.html\" rel=\"nofollow noreferrer\">wc_get_featured_product_ids()</a> too:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'product',\n 'posts_per_page' => 6,\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'post__in' => wc_get_featured_product_ids(),\n);\n\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>I hope it helps!</p>\n"
},
{
"answer_id": 304374,
"author": "cfx",
"author_id": 28957,
"author_profile": "https://wordpress.stackexchange.com/users/28957",
"pm_score": 3,
"selected": false,
"text": "<p>According to the <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query\" rel=\"noreferrer\">WooCommerce Wiki</a>:</p>\n\n<blockquote>\n <p><strong>Building custom WP_Queries or database queries [to retrieve products] is likely to break your code</strong> in future versions of WooCommerce as data moves towards custom tables for better performance.</p>\n</blockquote>\n\n<p>WooCommerce advocates using <code>wc_get_products()</code> or <code>WC_Product_Query()</code> instead of <code>WP_Query()</code> or <code>get_posts()</code>.</p>\n\n<p>I've written a post with the code I used to achieve what you want here: <a href=\"https://cfxdesign.com/create-a-custom-woocommerce-product-loop-the-right-way/\" rel=\"noreferrer\">https://cfxdesign.com/create-a-custom-woocommerce-product-loop-the-right-way/</a></p>\n"
},
{
"answer_id": 315190,
"author": "conschneider",
"author_id": 108696,
"author_profile": "https://wordpress.stackexchange.com/users/108696",
"pm_score": 1,
"selected": false,
"text": "<p>Based on: <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query\" rel=\"nofollow noreferrer\">https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query</a></p>\n\n<p>I would try: </p>\n\n<p>outside loop: </p>\n\n<pre><code>$args = array (\n'limit' => 6,\n'orderby' => 'title',\n'order' => 'ASC',\n'category' => $club_cat,\n'stock_status' => 'instock',\n'featured' => true,\n\n );\n\n $products = wc_get_products( $args );\n</code></pre>\n\n<p>in the loop: </p>\n\n<pre><code>$query = new WC_Product_Query( array(\n'limit' => 6,\n'orderby' => 'title',\n'order' => 'ASC',\n'category' => $club_cat,\n'stock_status' => 'instock',\n'featured' => true,\n'return' => 'ids',\n\n ) );\n\n $products = $query->get_products();\n</code></pre>\n"
},
{
"answer_id": 333357,
"author": "Dhaval",
"author_id": 164378,
"author_profile": "https://wordpress.stackexchange.com/users/164378",
"pm_score": 0,
"selected": false,
"text": "<pre><code><ul class=\"products\">\n <?php\n $args = array(\n 'post_type' => 'product',\n 'posts_per_page' => 12,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'product_visibility',\n 'field' => 'name',\n 'terms' => 'featured',\n ),\n ),\n );\n $loop = new WP_Query( $args );\n if ( $loop->have_posts() ) {\n while ( $loop->have_posts() ) : $loop->the_post();\n echo '<p>'.get_the_title().'</p>';\n endwhile;\n } else {\n echo __( 'No products found' );\n }\n wp_reset_postdata();\n ?>\n</ul><!--/.products-->\n</code></pre>\n"
},
{
"answer_id": 370913,
"author": "jameshwart lopez",
"author_id": 75608,
"author_profile": "https://wordpress.stackexchange.com/users/75608",
"pm_score": 1,
"selected": false,
"text": "<p>People should start using wc_get_products because woocommerce said this is the standard way of retrieving product. wc_get_products has an argument featured which just needs to be set to true. So the code is simply below.</p>\n<pre><code> <?php \n\n// Display featured products by category. on this case its "shirts" which is the slug of the category.\n$query_args = array(\n 'featured' => true, \n 'category' => array( 'shirts' ),\n);\n$products = wc_get_products( $query_args );\n\nglobal $post;\n$columns = wc_get_loop_prop( 'columns' );\n?>\n<div class="woocommerce columns-<?php echo esc_attr( $columns ); ?>">\n <?php\n woocommerce_product_loop_start();\n foreach ($products as $product) {\n $post = get_post($product->get_id());\n setup_postdata($post);\n wc_get_template_part('content', 'product');\n }\n wp_reset_postdata();\n woocommerce_product_loop_end();\n ?>\n</div>\n</code></pre>\n<p>See full post here: <a href=\"https://jameshwartlopez.com/plugin/get-featured-products-of-a-category/\" rel=\"nofollow noreferrer\">https://jameshwartlopez.com/plugin/get-featured-products-of-a-category/</a></p>\n"
},
{
"answer_id": 392894,
"author": "Chad Reitsma",
"author_id": 160601,
"author_profile": "https://wordpress.stackexchange.com/users/160601",
"pm_score": 0,
"selected": false,
"text": "<p>Bump for 2021 - You need to be using <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query\" rel=\"nofollow noreferrer\">wc_get_products()</a></p>\n<p>Also, the code example from Jameshwart (above) didn't work for me, this is how I set up the postdata & use wc_get_template. Tested & working.</p>\n<pre><code>$args = array(\n 'status' => 'publish',\n 'limit' => 20,\n 'paginate' => true, //must be true in order to get ->total\n 'return' => 'ids',\n);\n$products = wc_get_products( $args );\n\nif ($products->total >= 1):\n\n woocommerce_product_loop_start();\n\n foreach($products->products as $pid):\n\n do_action( 'woocommerce_shop_loop' );\n\n $product = get_post($pid);\n setup_postdata($GLOBALS['post'] =& $product);\n wc_get_template_part('content', 'product');\n\n endforeach;\n wp_reset_postdata();\n\n woocommerce_product_loop_end();\n\n\nendif; //we have products\n</code></pre>\n"
}
] |
2015/07/24
|
[
"https://wordpress.stackexchange.com/questions/195434",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76680/"
] |
I want to update my old website with WordPress but I got some problems...
Is it possible to create a website without domain name (before publish) and replace it with my old website domain name as soon as i finish building the new one?
Basically, I want to keep my old website (not built by WordPress) while I am working on the new web. Then use the domain name that I have for the old web to replace it with the new web that I will build in WordPress.
First I start building a new "free WordPress.com" but it's not in admin site, so i ran into lots of difficulties when I used it. So i want to start over and do it on admin site but I got problem with the domain now :(
Thank you!
|
Change your args to be like this:
```
$meta_query = WC()->query->get_meta_query();
$meta_query[] = array(
'key' => '_featured',
'value' => 'yes'
);
$args = array(
'post_type' => 'product',
'stock' => 1,
'showposts' => 6,
'orderby' => 'date',
'order' => 'DESC',
'meta_query' => $meta_query
);
```
If you go to wp-content/plugins/woocommerce/includes/class-wc-shortcodes.php (@595) you can find how it's done for WC shortcodes.
|
195,452 |
<p>I am using wp_schedule_event for Insert data every 1 Minutes in a teble. But here is some confusion where i have to add code for Insert.
Here is my code which add in functions.php in my theme. </p>
<pre><code>register_activation_hook(__FILE__, 'my_activation');
add_action('my_hourly_event', 'do_this_hourly');
function my_activation() {
wp_schedule_event(time(), 'minutes', 'my_hourly_event');
global $wpdb;
//INSERT INTO `wp_test`.`wp_options` (`option_id`, `option_name`, `option_value`, `autoload`) VALUES (NULL, 'database_options', 'hello', 'yes');
}
function do_this_hourly() {
$schedules['every_three_minutes'] = array(
'interval' => 60,
'display' => __( 'Every 1 Minutes', 'textdomain' )
);
return $schedules;
}
//deactive
register_deactivation_hook(__FILE__, 'my_deactivation');
function my_deactivation() {
wp_clear_scheduled_hook('my_hourly_event');
}
</code></pre>
|
[
{
"answer_id": 202739,
"author": "Hooman Askari",
"author_id": 31189,
"author_profile": "https://wordpress.stackexchange.com/users/31189",
"pm_score": 5,
"selected": true,
"text": "<p>Change your args to be like this:</p>\n\n<pre><code>$meta_query = WC()->query->get_meta_query();\n$meta_query[] = array(\n 'key' => '_featured',\n 'value' => 'yes'\n);\n$args = array(\n 'post_type' => 'product',\n 'stock' => 1,\n 'showposts' => 6,\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'meta_query' => $meta_query\n);\n</code></pre>\n\n<p>If you go to wp-content/plugins/woocommerce/includes/class-wc-shortcodes.php (@595) you can find how it's done for WC shortcodes.</p>\n"
},
{
"answer_id": 232010,
"author": "Aamer Shahzad",
"author_id": 42772,
"author_profile": "https://wordpress.stackexchange.com/users/42772",
"pm_score": 0,
"selected": false,
"text": "<p>if you take a look in the database in <code>wp_postmeta</code> table you will see <code>meta_key</code> will be <code>_featured</code> and <code>meta_value</code> will be <code>yes</code> or <code>no</code> so instead of value <code>0</code> or <code>1</code> write <code>yes</code> or <code>no</code> </p>\n\n<pre><code><?php\n $q = new WP_Query([\n 'post_type' => 'product',\n 'stock' => 1,\n 'showposts' => 3,\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'meta_query' => [ \n ['key' => '_featured', 'value' => 'yes' ]\n ]\n ]);\n if ( $q->have_posts() ) :\n while ( $q->have_posts() ) : $q->the_post();\n // display product info\n endwhile; wp_reset_query();\n endif;\n?>\n</code></pre>\n"
},
{
"answer_id": 266252,
"author": "dpruth",
"author_id": 78022,
"author_profile": "https://wordpress.stackexchange.com/users/78022",
"pm_score": 5,
"selected": false,
"text": "<p>This has changed in WooCommerce 3.0. It's not simply a meta_query, but now includes a tax_query. The arguments are now:</p>\n\n<pre><code> $meta_query = WC()->query->get_meta_query();\n $tax_query = WC()->query->get_tax_query();\n $tax_query[] = array(\n 'taxonomy' => 'product_visibility',\n 'field' => 'name',\n 'terms' => 'featured',\n 'operator' => 'IN',\n );\n\n $args = array(\n 'post_type' => 'product',\n 'post_status' => 'publish',\n 'ignore_sticky_posts' => 1,\n 'posts_per_page' => $atts['per_page'],\n 'orderby' => $atts['orderby'],\n 'order' => $atts['order'],\n 'meta_query' => $meta_query,\n 'tax_query' => $tax_query,\n );\n</code></pre>\n\n<p>See woocommerce/includes/class-wc-shortcodes.php</p>\n"
},
{
"answer_id": 289382,
"author": "Mostafa Norzade",
"author_id": 131388,
"author_profile": "https://wordpress.stackexchange.com/users/131388",
"pm_score": 3,
"selected": false,
"text": "<p>Featured Products Loop in WooCommerce 3</p>\n\n<pre><code><ul class=\"products\">\n<?php\n$args = array(\n 'post_type' => 'product',\n 'posts_per_page' => 12,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'product_visibility',\n 'field' => 'name',\n 'terms' => 'featured',\n ),\n ),\n );\n$loop = new WP_Query( $args );\nif ( $loop->have_posts() ) {\n while ( $loop->have_posts() ) : $loop->the_post();\n wc_get_template_part( 'content', 'product' );\n endwhile;\n} else {\n echo __( 'No products found' );\n}\nwp_reset_postdata();\n?>\n</code></pre>\n"
},
{
"answer_id": 302194,
"author": "Felipe Elia",
"author_id": 122788,
"author_profile": "https://wordpress.stackexchange.com/users/122788",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is quite old, but I've just shared an alternative solution <a href=\"https://stackoverflow.com/a/50081494/5970334\">here</a> and I think it can help those reaching this topic too.</p>\n\n<p>Instead of using <code>meta_query</code> or <code>tax_query</code>, you can use <a href=\"https://docs.woocommerce.com/wc-apidocs/function-wc_get_featured_product_ids.html\" rel=\"nofollow noreferrer\">wc_get_featured_product_ids()</a> too:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'product',\n 'posts_per_page' => 6,\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'post__in' => wc_get_featured_product_ids(),\n);\n\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>I hope it helps!</p>\n"
},
{
"answer_id": 304374,
"author": "cfx",
"author_id": 28957,
"author_profile": "https://wordpress.stackexchange.com/users/28957",
"pm_score": 3,
"selected": false,
"text": "<p>According to the <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query\" rel=\"noreferrer\">WooCommerce Wiki</a>:</p>\n\n<blockquote>\n <p><strong>Building custom WP_Queries or database queries [to retrieve products] is likely to break your code</strong> in future versions of WooCommerce as data moves towards custom tables for better performance.</p>\n</blockquote>\n\n<p>WooCommerce advocates using <code>wc_get_products()</code> or <code>WC_Product_Query()</code> instead of <code>WP_Query()</code> or <code>get_posts()</code>.</p>\n\n<p>I've written a post with the code I used to achieve what you want here: <a href=\"https://cfxdesign.com/create-a-custom-woocommerce-product-loop-the-right-way/\" rel=\"noreferrer\">https://cfxdesign.com/create-a-custom-woocommerce-product-loop-the-right-way/</a></p>\n"
},
{
"answer_id": 315190,
"author": "conschneider",
"author_id": 108696,
"author_profile": "https://wordpress.stackexchange.com/users/108696",
"pm_score": 1,
"selected": false,
"text": "<p>Based on: <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query\" rel=\"nofollow noreferrer\">https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query</a></p>\n\n<p>I would try: </p>\n\n<p>outside loop: </p>\n\n<pre><code>$args = array (\n'limit' => 6,\n'orderby' => 'title',\n'order' => 'ASC',\n'category' => $club_cat,\n'stock_status' => 'instock',\n'featured' => true,\n\n );\n\n $products = wc_get_products( $args );\n</code></pre>\n\n<p>in the loop: </p>\n\n<pre><code>$query = new WC_Product_Query( array(\n'limit' => 6,\n'orderby' => 'title',\n'order' => 'ASC',\n'category' => $club_cat,\n'stock_status' => 'instock',\n'featured' => true,\n'return' => 'ids',\n\n ) );\n\n $products = $query->get_products();\n</code></pre>\n"
},
{
"answer_id": 333357,
"author": "Dhaval",
"author_id": 164378,
"author_profile": "https://wordpress.stackexchange.com/users/164378",
"pm_score": 0,
"selected": false,
"text": "<pre><code><ul class=\"products\">\n <?php\n $args = array(\n 'post_type' => 'product',\n 'posts_per_page' => 12,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'product_visibility',\n 'field' => 'name',\n 'terms' => 'featured',\n ),\n ),\n );\n $loop = new WP_Query( $args );\n if ( $loop->have_posts() ) {\n while ( $loop->have_posts() ) : $loop->the_post();\n echo '<p>'.get_the_title().'</p>';\n endwhile;\n } else {\n echo __( 'No products found' );\n }\n wp_reset_postdata();\n ?>\n</ul><!--/.products-->\n</code></pre>\n"
},
{
"answer_id": 370913,
"author": "jameshwart lopez",
"author_id": 75608,
"author_profile": "https://wordpress.stackexchange.com/users/75608",
"pm_score": 1,
"selected": false,
"text": "<p>People should start using wc_get_products because woocommerce said this is the standard way of retrieving product. wc_get_products has an argument featured which just needs to be set to true. So the code is simply below.</p>\n<pre><code> <?php \n\n// Display featured products by category. on this case its "shirts" which is the slug of the category.\n$query_args = array(\n 'featured' => true, \n 'category' => array( 'shirts' ),\n);\n$products = wc_get_products( $query_args );\n\nglobal $post;\n$columns = wc_get_loop_prop( 'columns' );\n?>\n<div class="woocommerce columns-<?php echo esc_attr( $columns ); ?>">\n <?php\n woocommerce_product_loop_start();\n foreach ($products as $product) {\n $post = get_post($product->get_id());\n setup_postdata($post);\n wc_get_template_part('content', 'product');\n }\n wp_reset_postdata();\n woocommerce_product_loop_end();\n ?>\n</div>\n</code></pre>\n<p>See full post here: <a href=\"https://jameshwartlopez.com/plugin/get-featured-products-of-a-category/\" rel=\"nofollow noreferrer\">https://jameshwartlopez.com/plugin/get-featured-products-of-a-category/</a></p>\n"
},
{
"answer_id": 392894,
"author": "Chad Reitsma",
"author_id": 160601,
"author_profile": "https://wordpress.stackexchange.com/users/160601",
"pm_score": 0,
"selected": false,
"text": "<p>Bump for 2021 - You need to be using <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query\" rel=\"nofollow noreferrer\">wc_get_products()</a></p>\n<p>Also, the code example from Jameshwart (above) didn't work for me, this is how I set up the postdata & use wc_get_template. Tested & working.</p>\n<pre><code>$args = array(\n 'status' => 'publish',\n 'limit' => 20,\n 'paginate' => true, //must be true in order to get ->total\n 'return' => 'ids',\n);\n$products = wc_get_products( $args );\n\nif ($products->total >= 1):\n\n woocommerce_product_loop_start();\n\n foreach($products->products as $pid):\n\n do_action( 'woocommerce_shop_loop' );\n\n $product = get_post($pid);\n setup_postdata($GLOBALS['post'] =& $product);\n wc_get_template_part('content', 'product');\n\n endforeach;\n wp_reset_postdata();\n\n woocommerce_product_loop_end();\n\n\nendif; //we have products\n</code></pre>\n"
}
] |
2015/07/24
|
[
"https://wordpress.stackexchange.com/questions/195452",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68882/"
] |
I am using wp\_schedule\_event for Insert data every 1 Minutes in a teble. But here is some confusion where i have to add code for Insert.
Here is my code which add in functions.php in my theme.
```
register_activation_hook(__FILE__, 'my_activation');
add_action('my_hourly_event', 'do_this_hourly');
function my_activation() {
wp_schedule_event(time(), 'minutes', 'my_hourly_event');
global $wpdb;
//INSERT INTO `wp_test`.`wp_options` (`option_id`, `option_name`, `option_value`, `autoload`) VALUES (NULL, 'database_options', 'hello', 'yes');
}
function do_this_hourly() {
$schedules['every_three_minutes'] = array(
'interval' => 60,
'display' => __( 'Every 1 Minutes', 'textdomain' )
);
return $schedules;
}
//deactive
register_deactivation_hook(__FILE__, 'my_deactivation');
function my_deactivation() {
wp_clear_scheduled_hook('my_hourly_event');
}
```
|
Change your args to be like this:
```
$meta_query = WC()->query->get_meta_query();
$meta_query[] = array(
'key' => '_featured',
'value' => 'yes'
);
$args = array(
'post_type' => 'product',
'stock' => 1,
'showposts' => 6,
'orderby' => 'date',
'order' => 'DESC',
'meta_query' => $meta_query
);
```
If you go to wp-content/plugins/woocommerce/includes/class-wc-shortcodes.php (@595) you can find how it's done for WC shortcodes.
|
195,465 |
<p>I am trying to get the categories of my custom post type in functions.php But it not return any value, when i run this query in any theme file it work fine. Here is my code</p>
<pre><code>function get_destinations(){
$args = array(
'type' => 'accomodation',
'child_of' => 0,
'parent' => '',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'facilitie',
'pad_counts' => false
);
$categories = get_categories($args);$destinations = array();
foreach ($categories as $cat) {
if($cat->cat_name != ''){
$destinations[$cat->cat_name] = $cat->cat_name;
}
}
return $destinations;
}
</code></pre>
<p>I am using <a href="https://en.bainternet.info/how-i-add-a-wordpress-metabox/" rel="nofollow">this</a> code to add <code>meta field</code>, now i have to pass the category to <code>select</code> tag which is </p>
<pre><code>$my_meta2->addSelect($prefix.'select_field_id',get_destinations(),array('name'=> 'Select Destination'));
</code></pre>
<p>The original code is like this, they pass the value in array.</p>
<pre><code>$my_meta->addSelect($prefix.'select_field_id',array('selectkey1'=>'Select Value1','selectkey2'=>'Select Value2'),array('name'=> 'My select ', 'std'=> array('selectkey2')));
</code></pre>
<p>But not getting any value, Any idea where i am wrong. Thanks</p>
|
[
{
"answer_id": 195481,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 1,
"selected": false,
"text": "<p>You are using third party code to generate those meta boxes, and I am not familiar with how that code works. In fact, based on your question I am not even sure exactly where the code fails. Your description of the problem is inadequate. I can point out that your code is overly complex. It can be simplified considerably:</p>\n\n<pre><code>function get_destinations(){\n // Using a post type\n $args = array(\n 'type' => 'book',\n 'taxonomy' => 'genre',\n ); \n $categories = get_terms($args); // changed to get_terms()\n\n if (!is_wp_error()) {\n $destinations = wp_list_pluck($categories,'cat_name');\n /* Convert to key=>value format\n I doubt this is actually necessary and can probably be omitted\n */\n $destinations = array_combine($destinations,$destinations);\n return $destinations;\n }\n}\nvar_dump(get_destinations());\n</code></pre>\n\n<ol>\n<li>Remove the default arguments. You don't need to repeat those.</li>\n<li>Use <code>get_terms()</code> as it returns a proper <code>WP_Error</code> object instead\nof only a part of one (at least on my install, which I may have\nbroken. I do that periodically). At any rate, <code>get_terms()</code> makes\nmore since as you are not retrieving \"categories\" but a custom\ntaxonomy.</li>\n<li>Verify that you have proper term results before trying to use them</li>\n<li>Use <code>wp_list_pluck()</code> to simplify the <code>foreach</code></li>\n</ol>\n\n<p>As far as Core code, I only see three places where this can fail:</p>\n\n<ol>\n<li>The post type is wrong</li>\n<li>The taxonomy is wrong</li>\n<li>There are not posts in the type/taxonomy</li>\n</ol>\n"
},
{
"answer_id": 195482,
"author": "Josh Riser",
"author_id": 76601,
"author_profile": "https://wordpress.stackexchange.com/users/76601",
"pm_score": 0,
"selected": false,
"text": "<p>Check the Parameters section in the WordPress Codex for <strong>get_categories</strong>.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_categories#Parameters\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_categories#Parameters</a></p>\n\n<p>The <strong>type</strong> parameter only accepts 2 values (post & link) and you are trying to use <strong>accomodation</strong>.</p>\n\n<p>What you are probably wanting is <strong>get_terms</strong>.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_terms\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_terms</a></p>\n\n<p>So you will use this instead of <strong>get_categories</strong>.</p>\n\n<pre><code>$categories = get_terms('facilitie');\n</code></pre>\n\n<p>For what you are trying to do you probably don't need any <strong>$args</strong> array.</p>\n\n<p>Then in your <strong>foreach</strong> you will just want to change <strong>$cat->cat_name</strong> to <strong>$cat->name</strong>.</p>\n"
},
{
"answer_id": 249944,
"author": "Samyappa",
"author_id": 72738,
"author_profile": "https://wordpress.stackexchange.com/users/72738",
"pm_score": 1,
"selected": false,
"text": "<p>It Will work,</p>\n\n<pre><code>$cat_args = array(\n 'parent' => 0,\n 'hide_empty' =>0,\n 'order' => 'ASC',\n );\n $categories = get_categories($cat_args);\n foreach($categories as $category){\n echo get_cat_name($category->term_id); \n }\n</code></pre>\n"
},
{
"answer_id": 249953,
"author": "Mohamed Rihan",
"author_id": 85768,
"author_profile": "https://wordpress.stackexchange.com/users/85768",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function get_cat_val(){\n\n $taxonomies = array('YOUR_CAT_SLUG');\n\n $args = array(\n 'order' => 'ASC',\n 'hide_empty' => false,\n 'hierarchical' => true \n ); \n\n $terms = get_terms($taxonomies, $args);\n\n print_r($terms);\n\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>global $post;\n$term_class = array();\n\n$terms = get_the_terms( $post->ID, 'YOUR CAT SLUG' );\n\nif ( $terms && ! is_wp_error( $terms ) ) {\n\n foreach ( $terms as $term ) {\n $term_class[] = $term->slug;\n }\n\n}\n</code></pre>\n"
}
] |
2015/07/24
|
[
"https://wordpress.stackexchange.com/questions/195465",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/55372/"
] |
I am trying to get the categories of my custom post type in functions.php But it not return any value, when i run this query in any theme file it work fine. Here is my code
```
function get_destinations(){
$args = array(
'type' => 'accomodation',
'child_of' => 0,
'parent' => '',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'facilitie',
'pad_counts' => false
);
$categories = get_categories($args);$destinations = array();
foreach ($categories as $cat) {
if($cat->cat_name != ''){
$destinations[$cat->cat_name] = $cat->cat_name;
}
}
return $destinations;
}
```
I am using [this](https://en.bainternet.info/how-i-add-a-wordpress-metabox/) code to add `meta field`, now i have to pass the category to `select` tag which is
```
$my_meta2->addSelect($prefix.'select_field_id',get_destinations(),array('name'=> 'Select Destination'));
```
The original code is like this, they pass the value in array.
```
$my_meta->addSelect($prefix.'select_field_id',array('selectkey1'=>'Select Value1','selectkey2'=>'Select Value2'),array('name'=> 'My select ', 'std'=> array('selectkey2')));
```
But not getting any value, Any idea where i am wrong. Thanks
|
You are using third party code to generate those meta boxes, and I am not familiar with how that code works. In fact, based on your question I am not even sure exactly where the code fails. Your description of the problem is inadequate. I can point out that your code is overly complex. It can be simplified considerably:
```
function get_destinations(){
// Using a post type
$args = array(
'type' => 'book',
'taxonomy' => 'genre',
);
$categories = get_terms($args); // changed to get_terms()
if (!is_wp_error()) {
$destinations = wp_list_pluck($categories,'cat_name');
/* Convert to key=>value format
I doubt this is actually necessary and can probably be omitted
*/
$destinations = array_combine($destinations,$destinations);
return $destinations;
}
}
var_dump(get_destinations());
```
1. Remove the default arguments. You don't need to repeat those.
2. Use `get_terms()` as it returns a proper `WP_Error` object instead
of only a part of one (at least on my install, which I may have
broken. I do that periodically). At any rate, `get_terms()` makes
more since as you are not retrieving "categories" but a custom
taxonomy.
3. Verify that you have proper term results before trying to use them
4. Use `wp_list_pluck()` to simplify the `foreach`
As far as Core code, I only see three places where this can fail:
1. The post type is wrong
2. The taxonomy is wrong
3. There are not posts in the type/taxonomy
|
195,557 |
<p>I've created a custom child theme of parent theme Cordillera.</p>
<p>This is my child theme's header.php (<code><head></code>): </p>
<pre><code><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<?php wp_head();?>
<?php
global $enable_home_page;
$banner = "";
$home_banner_type = cordillera_options_array("home_banner_type",1);
$enable_home_page = cordillera_options_array("enable_home_page");
if( is_front_page() ){
$class = "homepage";
$banner = cordillera_get_banner($home_banner_type);
}
else
{
$class = "sitepage";
}
?>
<link href='http://fonts.googleapis.com/css?family=Waiting+for+the+Sunrise' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<?php if(!(is_front_page())) { ?>
<!-- non-front-page CSS -->
<style>
html {
background-color: transparent;
background: url('<?php echo get_stylesheet_directory_uri(); ?>/images/bg-product.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
<!-- END non-front-page CSS -->
</style>
<?php } ?>
<?php if(is_page(6)) { ?>
<!-- shop page CSS -->
<style>
.blog-main {
background-color: transparent !important;
}
</style>
<!-- shop page CSS -->
<?php } ?>
</head>
</code></pre>
<p>I haven't included a link to my child theme's <code>style.css</code> in this file, instead using:</p>
<pre><code>add_action( 'wp_enqueue_scripts', function() {
wp_register_style( 'childstyle', get_stylesheet_uri());
wp_enqueue_style( 'childstyle', get_stylesheet_uri());
});
</code></pre>
<p>in my child theme's <code>functions.php</code>.</p>
<p>However, when logged into Wordpress admin, and viewing WooCommerce pages, some of the admin tool bar links are being colored by my child theme's <code>style.css</code>.</p>
<p><a href="https://i.stack.imgur.com/EaXTh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EaXTh.png" alt="enter image description here"></a></p>
<p>How can I prevent this? Thanks.</p>
|
[
{
"answer_id": 196512,
"author": "Syed Priom",
"author_id": 48577,
"author_profile": "https://wordpress.stackexchange.com/users/48577",
"pm_score": -1,
"selected": false,
"text": "<p>What I'd try to do is applying <code>!important</code> to wp-admin native styles. But that would be costly because I would need full control of core files, and I would lose all the styles when upgrading to newer version of wordpress.</p>\n\n<p>If I don't want to mess with native wordpress code and do it specifically with the theme, I'd try to have unique classes for the links and all the theme's conflicting elements with admin area. Like, if I wrap my whole theme in <code><div id=\"viewport\"></code> and then in my theme file I do #viewport <code>a{color: yellow !important;}</code> I guess it would work.</p>\n\n<p>That's all I can think of, may be there would be better way just to prioritize execution of the CSS files by using a custom filter.</p>\n"
},
{
"answer_id": 196518,
"author": "denis.stoyanov",
"author_id": 76287,
"author_profile": "https://wordpress.stackexchange.com/users/76287",
"pm_score": 2,
"selected": true,
"text": "<p>Restructure your CSS files and remove <code>!important</code> rules from your <code>.css</code> files and use proper markup (classes, IDs and etc.).</p>\n\n<p>e.g.</p>\n\n<pre><code>a, .entry-summary a, .entry-content a {\n color: #06F !important;\n font-weight: 400;\n}\n</code></pre>\n\n<p>Judging from the test WS which was found with site: search in Google using the URL in your Facebook profile (Temper Temper).</p>\n\n<p><strong>Edit 1</strong>: Although <code>!important</code> rules can be handy from time to time, usually they broke the structure especially if they are not used with proper and detailed planning. </p>\n"
}
] |
2015/07/25
|
[
"https://wordpress.stackexchange.com/questions/195557",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3206/"
] |
I've created a custom child theme of parent theme Cordillera.
This is my child theme's header.php (`<head>`):
```
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<?php wp_head();?>
<?php
global $enable_home_page;
$banner = "";
$home_banner_type = cordillera_options_array("home_banner_type",1);
$enable_home_page = cordillera_options_array("enable_home_page");
if( is_front_page() ){
$class = "homepage";
$banner = cordillera_get_banner($home_banner_type);
}
else
{
$class = "sitepage";
}
?>
<link href='http://fonts.googleapis.com/css?family=Waiting+for+the+Sunrise' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<?php if(!(is_front_page())) { ?>
<!-- non-front-page CSS -->
<style>
html {
background-color: transparent;
background: url('<?php echo get_stylesheet_directory_uri(); ?>/images/bg-product.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
<!-- END non-front-page CSS -->
</style>
<?php } ?>
<?php if(is_page(6)) { ?>
<!-- shop page CSS -->
<style>
.blog-main {
background-color: transparent !important;
}
</style>
<!-- shop page CSS -->
<?php } ?>
</head>
```
I haven't included a link to my child theme's `style.css` in this file, instead using:
```
add_action( 'wp_enqueue_scripts', function() {
wp_register_style( 'childstyle', get_stylesheet_uri());
wp_enqueue_style( 'childstyle', get_stylesheet_uri());
});
```
in my child theme's `functions.php`.
However, when logged into Wordpress admin, and viewing WooCommerce pages, some of the admin tool bar links are being colored by my child theme's `style.css`.
[](https://i.stack.imgur.com/EaXTh.png)
How can I prevent this? Thanks.
|
Restructure your CSS files and remove `!important` rules from your `.css` files and use proper markup (classes, IDs and etc.).
e.g.
```
a, .entry-summary a, .entry-content a {
color: #06F !important;
font-weight: 400;
}
```
Judging from the test WS which was found with site: search in Google using the URL in your Facebook profile (Temper Temper).
**Edit 1**: Although `!important` rules can be handy from time to time, usually they broke the structure especially if they are not used with proper and detailed planning.
|
195,565 |
<p>I've been trying for hours if not a day to try and get my custom <code>search.php</code> and <code>searchform.php</code> to work and still no success. I've read a lot on these two templates and still no success.</p>
<p>Here is my <code>search.php</code>:</p>
<pre><code><div class="post-wrap">
<?php if ( have_posts() ) : while (have_posts()) : the_post(); ?>
<?php the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); ?>
<?php the_excerpt(); ?>
<?php endwhile; else: ?>
<p>Woops There is no post yet</p>
<?php endif; ?>
</div><!-- /.social-media-posts -->
</code></pre>
<p>Here is my <code>searchform.php</code>:</p>
<pre><code><form action="<?php echo home_url( '/' ); ?>" id="searchform" class="search-form" method="get" role="search">
<input type="text" id="s" placeholder="Search" class="search-field">
<input type="submit" value="&#xf002;" id="searchsubmit" class="search-submit">
<a class="search-close" href="#"><i class="fa fa-times-circle"></i></a>
</form>
</code></pre>
<p>And finally, this is what I use to call my <code>searchform.php</code> in my navigation template:</p>
<pre><code><?php get_searchform(); ?>
</code></pre>
<p>Still nothing works, I'm getting a little discouraged. I would appreciate any help. Thanks!</p>
|
[
{
"answer_id": 196512,
"author": "Syed Priom",
"author_id": 48577,
"author_profile": "https://wordpress.stackexchange.com/users/48577",
"pm_score": -1,
"selected": false,
"text": "<p>What I'd try to do is applying <code>!important</code> to wp-admin native styles. But that would be costly because I would need full control of core files, and I would lose all the styles when upgrading to newer version of wordpress.</p>\n\n<p>If I don't want to mess with native wordpress code and do it specifically with the theme, I'd try to have unique classes for the links and all the theme's conflicting elements with admin area. Like, if I wrap my whole theme in <code><div id=\"viewport\"></code> and then in my theme file I do #viewport <code>a{color: yellow !important;}</code> I guess it would work.</p>\n\n<p>That's all I can think of, may be there would be better way just to prioritize execution of the CSS files by using a custom filter.</p>\n"
},
{
"answer_id": 196518,
"author": "denis.stoyanov",
"author_id": 76287,
"author_profile": "https://wordpress.stackexchange.com/users/76287",
"pm_score": 2,
"selected": true,
"text": "<p>Restructure your CSS files and remove <code>!important</code> rules from your <code>.css</code> files and use proper markup (classes, IDs and etc.).</p>\n\n<p>e.g.</p>\n\n<pre><code>a, .entry-summary a, .entry-content a {\n color: #06F !important;\n font-weight: 400;\n}\n</code></pre>\n\n<p>Judging from the test WS which was found with site: search in Google using the URL in your Facebook profile (Temper Temper).</p>\n\n<p><strong>Edit 1</strong>: Although <code>!important</code> rules can be handy from time to time, usually they broke the structure especially if they are not used with proper and detailed planning. </p>\n"
}
] |
2015/07/25
|
[
"https://wordpress.stackexchange.com/questions/195565",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/55212/"
] |
I've been trying for hours if not a day to try and get my custom `search.php` and `searchform.php` to work and still no success. I've read a lot on these two templates and still no success.
Here is my `search.php`:
```
<div class="post-wrap">
<?php if ( have_posts() ) : while (have_posts()) : the_post(); ?>
<?php the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); ?>
<?php the_excerpt(); ?>
<?php endwhile; else: ?>
<p>Woops There is no post yet</p>
<?php endif; ?>
</div><!-- /.social-media-posts -->
```
Here is my `searchform.php`:
```
<form action="<?php echo home_url( '/' ); ?>" id="searchform" class="search-form" method="get" role="search">
<input type="text" id="s" placeholder="Search" class="search-field">
<input type="submit" value="" id="searchsubmit" class="search-submit">
<a class="search-close" href="#"><i class="fa fa-times-circle"></i></a>
</form>
```
And finally, this is what I use to call my `searchform.php` in my navigation template:
```
<?php get_searchform(); ?>
```
Still nothing works, I'm getting a little discouraged. I would appreciate any help. Thanks!
|
Restructure your CSS files and remove `!important` rules from your `.css` files and use proper markup (classes, IDs and etc.).
e.g.
```
a, .entry-summary a, .entry-content a {
color: #06F !important;
font-weight: 400;
}
```
Judging from the test WS which was found with site: search in Google using the URL in your Facebook profile (Temper Temper).
**Edit 1**: Although `!important` rules can be handy from time to time, usually they broke the structure especially if they are not used with proper and detailed planning.
|
195,576 |
<p>I have been trying to make my Wordpress Gallery responsive with the help from another post:
<a href="https://wordpress.stackexchange.com/questions/185961/making-wordpress-gallery-gallery-item-responsive/185965#185965">Making WordPress Gallery (.gallery-item) Responsive?</a></p>
<p>I would also like the original 5-column gallery to display three columns on a tablet. I have used the following css:</p>
<pre><code>/* For displaying 3 columns on tablet */
@media only screen and (max-width: 800px) {
.gallery-columns-5 .gallery-item {
width: 33% !important;
}
}
</code></pre>
<p>This works and is now displaying three columns. But it leaves a blank space after every 5th picture. As suggested in the other post i tried</p>
<pre><code>.gallery-columns-5 .gallery-item:nth-child(5n+1) {
clear: none;
}
</code></pre>
<p>But this does not seem to work. Does anyone know how to get rid of the blank spaces and still display the page correctly on both tablets and desktops?</p>
<p>The URL for the page is: <a href="http://www.xn--l-guiden-44a.dk/billede-test" rel="nofollow noreferrer">http://www.xn--l-guiden-44a.dk/billede-test</a></p>
|
[
{
"answer_id": 196512,
"author": "Syed Priom",
"author_id": 48577,
"author_profile": "https://wordpress.stackexchange.com/users/48577",
"pm_score": -1,
"selected": false,
"text": "<p>What I'd try to do is applying <code>!important</code> to wp-admin native styles. But that would be costly because I would need full control of core files, and I would lose all the styles when upgrading to newer version of wordpress.</p>\n\n<p>If I don't want to mess with native wordpress code and do it specifically with the theme, I'd try to have unique classes for the links and all the theme's conflicting elements with admin area. Like, if I wrap my whole theme in <code><div id=\"viewport\"></code> and then in my theme file I do #viewport <code>a{color: yellow !important;}</code> I guess it would work.</p>\n\n<p>That's all I can think of, may be there would be better way just to prioritize execution of the CSS files by using a custom filter.</p>\n"
},
{
"answer_id": 196518,
"author": "denis.stoyanov",
"author_id": 76287,
"author_profile": "https://wordpress.stackexchange.com/users/76287",
"pm_score": 2,
"selected": true,
"text": "<p>Restructure your CSS files and remove <code>!important</code> rules from your <code>.css</code> files and use proper markup (classes, IDs and etc.).</p>\n\n<p>e.g.</p>\n\n<pre><code>a, .entry-summary a, .entry-content a {\n color: #06F !important;\n font-weight: 400;\n}\n</code></pre>\n\n<p>Judging from the test WS which was found with site: search in Google using the URL in your Facebook profile (Temper Temper).</p>\n\n<p><strong>Edit 1</strong>: Although <code>!important</code> rules can be handy from time to time, usually they broke the structure especially if they are not used with proper and detailed planning. </p>\n"
}
] |
2015/07/25
|
[
"https://wordpress.stackexchange.com/questions/195576",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76769/"
] |
I have been trying to make my Wordpress Gallery responsive with the help from another post:
[Making WordPress Gallery (.gallery-item) Responsive?](https://wordpress.stackexchange.com/questions/185961/making-wordpress-gallery-gallery-item-responsive/185965#185965)
I would also like the original 5-column gallery to display three columns on a tablet. I have used the following css:
```
/* For displaying 3 columns on tablet */
@media only screen and (max-width: 800px) {
.gallery-columns-5 .gallery-item {
width: 33% !important;
}
}
```
This works and is now displaying three columns. But it leaves a blank space after every 5th picture. As suggested in the other post i tried
```
.gallery-columns-5 .gallery-item:nth-child(5n+1) {
clear: none;
}
```
But this does not seem to work. Does anyone know how to get rid of the blank spaces and still display the page correctly on both tablets and desktops?
The URL for the page is: <http://www.xn--l-guiden-44a.dk/billede-test>
|
Restructure your CSS files and remove `!important` rules from your `.css` files and use proper markup (classes, IDs and etc.).
e.g.
```
a, .entry-summary a, .entry-content a {
color: #06F !important;
font-weight: 400;
}
```
Judging from the test WS which was found with site: search in Google using the URL in your Facebook profile (Temper Temper).
**Edit 1**: Although `!important` rules can be handy from time to time, usually they broke the structure especially if they are not used with proper and detailed planning.
|
195,603 |
<p>How to add users roles dropdown in registration in wordpress</p>
<pre><code> function myplugin_register_form() {
global $wp_roles;
echo '<select name="role">';
foreach ( $wp_roles->roles as $key=>$value ):
echo '<option value="'.$key.'">'.$value['name'].'</option>';
endforeach;
echo '</select>';
}
add_action( 'register_form', 'myplugin_register_form' );
add_action( 'user_register', 'myplugin_user_register' );
function myplugin_user_register( $user_id ) {
if ( ! empty( $_POST['role'] ) ) {
update_user_meta( $user_id, 'role', trim( $_POST['role'] ) );
}
}
</code></pre>
<p>i used this code in functions.php but not working regards</p>
|
[
{
"answer_id": 195604,
"author": "sohan",
"author_id": 69017,
"author_profile": "https://wordpress.stackexchange.com/users/69017",
"pm_score": -1,
"selected": false,
"text": "<pre><code><?php global $wp_roles; ?>\n\n<select name=\"role\">\n<?php foreach ( $wp_roles->roles as $key=>$value ): ?>\n<option value=\"<?php echo $key; ?>\"><?php echo $value['name']; ?></option>\n<?php endforeach; ?>\n</select>\n</code></pre>\n"
},
{
"answer_id": 195636,
"author": "Webloper",
"author_id": 29035,
"author_profile": "https://wordpress.stackexchange.com/users/29035",
"pm_score": 4,
"selected": true,
"text": "<ol>\n<li><a href=\"https://codex.wordpress.org/Customizing_the_Registration_Form\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Customizing_the_Registration_Form</a></li>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/wp_update_user\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_update_user</a></li>\n</ol>\n\n<p>Instead of <strong>update_user_meta</strong> function in user_register hook use <strong>wp_update_user</strong></p>\n\n<p>Following is the working example:</p>\n\n<pre><code>//1. Add a new form element...\nadd_action( 'register_form', 'myplugin_register_form' );\nfunction myplugin_register_form() {\n\n global $wp_roles;\n\n echo '<select name=\"role\" class=\"input\">';\n foreach ( $wp_roles->roles as $key=>$value ) {\n // Exclude default roles such as administrator etc. Add your own\n if ( ! in_array( $value['name'], [ 'Administrator', 'Contributor', ] ) {\n echo '<option value=\"'.$key.'\">'.$value['name'].'</option>';\n }\n }\n echo '</select>';\n}\n\n//2. Add validation.\nadd_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 );\nfunction myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) {\n\n if ( empty( $_POST['role'] ) || ! empty( $_POST['role'] ) && trim( $_POST['role'] ) == '' ) {\n $errors->add( 'role_error', __( '<strong>ERROR</strong>: You must include a role.', 'mydomain' ) );\n }\n\n return $errors;\n}\n\n//3. Finally, save our extra registration user meta.\nadd_action( 'user_register', 'myplugin_user_register' );\nfunction myplugin_user_register( $user_id ) {\n\n $user_id = wp_update_user( array( 'ID' => $user_id, 'role' => $_POST['role'] ) );\n}\n</code></pre>\n"
}
] |
2015/07/26
|
[
"https://wordpress.stackexchange.com/questions/195603",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76780/"
] |
How to add users roles dropdown in registration in wordpress
```
function myplugin_register_form() {
global $wp_roles;
echo '<select name="role">';
foreach ( $wp_roles->roles as $key=>$value ):
echo '<option value="'.$key.'">'.$value['name'].'</option>';
endforeach;
echo '</select>';
}
add_action( 'register_form', 'myplugin_register_form' );
add_action( 'user_register', 'myplugin_user_register' );
function myplugin_user_register( $user_id ) {
if ( ! empty( $_POST['role'] ) ) {
update_user_meta( $user_id, 'role', trim( $_POST['role'] ) );
}
}
```
i used this code in functions.php but not working regards
|
1. <https://codex.wordpress.org/Customizing_the_Registration_Form>
2. <https://codex.wordpress.org/Function_Reference/wp_update_user>
Instead of **update\_user\_meta** function in user\_register hook use **wp\_update\_user**
Following is the working example:
```
//1. Add a new form element...
add_action( 'register_form', 'myplugin_register_form' );
function myplugin_register_form() {
global $wp_roles;
echo '<select name="role" class="input">';
foreach ( $wp_roles->roles as $key=>$value ) {
// Exclude default roles such as administrator etc. Add your own
if ( ! in_array( $value['name'], [ 'Administrator', 'Contributor', ] ) {
echo '<option value="'.$key.'">'.$value['name'].'</option>';
}
}
echo '</select>';
}
//2. Add validation.
add_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 );
function myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) {
if ( empty( $_POST['role'] ) || ! empty( $_POST['role'] ) && trim( $_POST['role'] ) == '' ) {
$errors->add( 'role_error', __( '<strong>ERROR</strong>: You must include a role.', 'mydomain' ) );
}
return $errors;
}
//3. Finally, save our extra registration user meta.
add_action( 'user_register', 'myplugin_user_register' );
function myplugin_user_register( $user_id ) {
$user_id = wp_update_user( array( 'ID' => $user_id, 'role' => $_POST['role'] ) );
}
```
|
195,631 |
<p>Hello all i am struggling for days now, and i hope one of you can help me
i have a custom post type called events and i like to show only events that date is today and upcoming but i couldnt get it to work , what am i doing wrong ?</p>
<p>here is my code so far: </p>
<pre><code><?php
$paged = ( get_query_var('paged') ) ?get_query_var('paged') : 1;
$today = time();
$events = new WP_Query(array(
'post_type' => 'events',
'posts_per_page' => '15',
'paged' => $paged,
'meta_query' => array(
array(
'key' => 'closingdate',
'compare' => '>=',
'value' => $today,
)
),
'meta_key' => 'closingdate',
'orderby' => 'meta_value',
'order' => 'DESC',
));
?>
<?php if ($events->have_posts()) : while ($events->have_posts()) : $events->the_post();?>
<div class="row">
<div class="cell_left"><p><a title="<?php the_title(); ?>" href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></p></div>
<div class="cell"><p class="posted"><?php echo date('d-m-Y', strtotime(get_post_meta($post->ID, "closingdate",true)));?></p></div>
</div>
<?php endwhile;?>
</div>
<div class="navigation">
<?php wp_pagenavi( array( 'query' => $events ) ); ?>
<?php wp_reset_query();?>
</code></pre>
|
[
{
"answer_id": 195604,
"author": "sohan",
"author_id": 69017,
"author_profile": "https://wordpress.stackexchange.com/users/69017",
"pm_score": -1,
"selected": false,
"text": "<pre><code><?php global $wp_roles; ?>\n\n<select name=\"role\">\n<?php foreach ( $wp_roles->roles as $key=>$value ): ?>\n<option value=\"<?php echo $key; ?>\"><?php echo $value['name']; ?></option>\n<?php endforeach; ?>\n</select>\n</code></pre>\n"
},
{
"answer_id": 195636,
"author": "Webloper",
"author_id": 29035,
"author_profile": "https://wordpress.stackexchange.com/users/29035",
"pm_score": 4,
"selected": true,
"text": "<ol>\n<li><a href=\"https://codex.wordpress.org/Customizing_the_Registration_Form\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Customizing_the_Registration_Form</a></li>\n<li><a href=\"https://codex.wordpress.org/Function_Reference/wp_update_user\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_update_user</a></li>\n</ol>\n\n<p>Instead of <strong>update_user_meta</strong> function in user_register hook use <strong>wp_update_user</strong></p>\n\n<p>Following is the working example:</p>\n\n<pre><code>//1. Add a new form element...\nadd_action( 'register_form', 'myplugin_register_form' );\nfunction myplugin_register_form() {\n\n global $wp_roles;\n\n echo '<select name=\"role\" class=\"input\">';\n foreach ( $wp_roles->roles as $key=>$value ) {\n // Exclude default roles such as administrator etc. Add your own\n if ( ! in_array( $value['name'], [ 'Administrator', 'Contributor', ] ) {\n echo '<option value=\"'.$key.'\">'.$value['name'].'</option>';\n }\n }\n echo '</select>';\n}\n\n//2. Add validation.\nadd_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 );\nfunction myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) {\n\n if ( empty( $_POST['role'] ) || ! empty( $_POST['role'] ) && trim( $_POST['role'] ) == '' ) {\n $errors->add( 'role_error', __( '<strong>ERROR</strong>: You must include a role.', 'mydomain' ) );\n }\n\n return $errors;\n}\n\n//3. Finally, save our extra registration user meta.\nadd_action( 'user_register', 'myplugin_user_register' );\nfunction myplugin_user_register( $user_id ) {\n\n $user_id = wp_update_user( array( 'ID' => $user_id, 'role' => $_POST['role'] ) );\n}\n</code></pre>\n"
}
] |
2015/07/26
|
[
"https://wordpress.stackexchange.com/questions/195631",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/20808/"
] |
Hello all i am struggling for days now, and i hope one of you can help me
i have a custom post type called events and i like to show only events that date is today and upcoming but i couldnt get it to work , what am i doing wrong ?
here is my code so far:
```
<?php
$paged = ( get_query_var('paged') ) ?get_query_var('paged') : 1;
$today = time();
$events = new WP_Query(array(
'post_type' => 'events',
'posts_per_page' => '15',
'paged' => $paged,
'meta_query' => array(
array(
'key' => 'closingdate',
'compare' => '>=',
'value' => $today,
)
),
'meta_key' => 'closingdate',
'orderby' => 'meta_value',
'order' => 'DESC',
));
?>
<?php if ($events->have_posts()) : while ($events->have_posts()) : $events->the_post();?>
<div class="row">
<div class="cell_left"><p><a title="<?php the_title(); ?>" href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></p></div>
<div class="cell"><p class="posted"><?php echo date('d-m-Y', strtotime(get_post_meta($post->ID, "closingdate",true)));?></p></div>
</div>
<?php endwhile;?>
</div>
<div class="navigation">
<?php wp_pagenavi( array( 'query' => $events ) ); ?>
<?php wp_reset_query();?>
```
|
1. <https://codex.wordpress.org/Customizing_the_Registration_Form>
2. <https://codex.wordpress.org/Function_Reference/wp_update_user>
Instead of **update\_user\_meta** function in user\_register hook use **wp\_update\_user**
Following is the working example:
```
//1. Add a new form element...
add_action( 'register_form', 'myplugin_register_form' );
function myplugin_register_form() {
global $wp_roles;
echo '<select name="role" class="input">';
foreach ( $wp_roles->roles as $key=>$value ) {
// Exclude default roles such as administrator etc. Add your own
if ( ! in_array( $value['name'], [ 'Administrator', 'Contributor', ] ) {
echo '<option value="'.$key.'">'.$value['name'].'</option>';
}
}
echo '</select>';
}
//2. Add validation.
add_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 );
function myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) {
if ( empty( $_POST['role'] ) || ! empty( $_POST['role'] ) && trim( $_POST['role'] ) == '' ) {
$errors->add( 'role_error', __( '<strong>ERROR</strong>: You must include a role.', 'mydomain' ) );
}
return $errors;
}
//3. Finally, save our extra registration user meta.
add_action( 'user_register', 'myplugin_user_register' );
function myplugin_user_register( $user_id ) {
$user_id = wp_update_user( array( 'ID' => $user_id, 'role' => $_POST['role'] ) );
}
```
|
195,634 |
<p>I am using <a href="http://ultimate%20member%20plugin" rel="nofollow">UltimateMember</a> and I have the settings configured that admin must approve registered users first. I now want to display the approved users meta information like faculty, email, etc. in the theme. So in this page template I've the following block of code to get all registered users information :</p>
<pre><code><?php
$args = array(
'role' => 'contributor',
);
$users = get_users( $args );
foreach ( $users as $user ) {
echo '<span>' . esc_html( $user->user_email ) . '</span>';
echo '<span>' . esc_html( $user->faculty ) . '</span>';
echo '<span>' . esc_html( $user->graduation_year ) . '</span>';
}
</code></pre>
<p>The problem is, that my code block is displaying all registered users information weather it is approved by admin or not.</p>
|
[
{
"answer_id": 195647,
"author": "Webloper",
"author_id": 29035,
"author_profile": "https://wordpress.stackexchange.com/users/29035",
"pm_score": 3,
"selected": true,
"text": "<p>I assume your WP settings is <br/></p>\n\n<ol>\n<li>New User Default Role = contributor</li>\n</ol>\n\n<p>If yes, so this block of code shows all the contributor's with account_status = approved;</p>\n\n<pre><code>$args = array(\n 'role' => 'contributor',\n 'meta_key' => 'account_status',\n 'meta_value' => 'approved'\n);\n\n$users = get_users($args);\n\nforeach ($users as $user) {\n echo '<pre>';\n print_r( $user );\n echo '</pre>';\n}\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_users\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_users</a></p>\n"
},
{
"answer_id": 213353,
"author": "Jhemalyn Rabanzo",
"author_id": 86098,
"author_profile": "https://wordpress.stackexchange.com/users/86098",
"pm_score": 0,
"selected": false,
"text": "<p>The plugin called Ultimate Member has this capability via the Ultimate Member settings > User roll.</p>\n\n<p>Plugin URL: <a href=\"https://wordpress.org/plugins/ultimate-member/\" rel=\"nofollow\">https://wordpress.org/plugins/ultimate-member/</a></p>\n"
}
] |
2015/07/26
|
[
"https://wordpress.stackexchange.com/questions/195634",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62794/"
] |
I am using [UltimateMember](http://ultimate%20member%20plugin) and I have the settings configured that admin must approve registered users first. I now want to display the approved users meta information like faculty, email, etc. in the theme. So in this page template I've the following block of code to get all registered users information :
```
<?php
$args = array(
'role' => 'contributor',
);
$users = get_users( $args );
foreach ( $users as $user ) {
echo '<span>' . esc_html( $user->user_email ) . '</span>';
echo '<span>' . esc_html( $user->faculty ) . '</span>';
echo '<span>' . esc_html( $user->graduation_year ) . '</span>';
}
```
The problem is, that my code block is displaying all registered users information weather it is approved by admin or not.
|
I assume your WP settings is
1. New User Default Role = contributor
If yes, so this block of code shows all the contributor's with account\_status = approved;
```
$args = array(
'role' => 'contributor',
'meta_key' => 'account_status',
'meta_value' => 'approved'
);
$users = get_users($args);
foreach ($users as $user) {
echo '<pre>';
print_r( $user );
echo '</pre>';
}
```
<https://codex.wordpress.org/Function_Reference/get_users>
|
195,641 |
<p><strong>Clarification</strong>: My default header image will not <strong>RE-display</strong> (by clicking suggested image) after it has been removed using theme customizer "Hide Image" option.</p>
<ol>
<li><p>I added theme support for Custom Header Image</p>
<pre><code>// Add Theme Support for Custom Header Image
add_theme_support( 'custom-header',
array(
'default-image' => get_template_directory_uri() . '/assets/img/hdr_earth.jpg',
'default-text-color' => '#e2f0d6',
'header-text' => true,
'uploads' => true,
'width' => 1140,
'height' => 200,
'wp-head-callback' => 'wpfw_style_header',
)
);
</code></pre></li>
<li><p>Inside the Theme Customizer I see the (default) image displayed as:</p>
<ul>
<li>The "Current Header" box, and </li>
<li>In the "Suggested" box</li>
</ul></li>
<li><p>I deleted the current header image by clicking the "Hide Image" button.</p></li>
</ol>
<p><strong>And this is where the problem started</strong> </p>
<p>When I attempt to <strong>re-add the default image</strong> by clicking on the "Suggested" (i.e. default) image...</p>
<ol>
<li>The image <strong>is displayed</strong> in the customizer window.</li>
<li>But the image <strong>will not save</strong>, so the image does not display on the web page.</li>
</ol>
<p>A <code>var_dump( get_header_image() );</code> returned <code>false</code>, so after reading the function in the core, I see this <code>if ( 'remove-header' == $url ) return false;</code>. </p>
<p>So a <code>var_dump( get_theme_mods() )</code> does indeed show <code>'header_image' => string 'remove-header' (length=13)</code>. </p>
<p>???</p>
<p>... now this is after I added the default image back <strong>and</strong> saved.</p>
<p>What am I missing?</p>
<p>The entire script (custom-header.php)</p>
<pre><code> if ( ! function_exists( 'wpfw_custom_header' ) ) {
function wpfw_custom_header() {
// Add theme Support for Custom Backgrounds
add_theme_support( 'custom-background',
array(
'default-color' => '#e2f0d6',
'default-image' => get_template_directory_uri() . '/assets/img/bgp-128x180.jpg',
)
);
// Add Theme Support for Custom Header Image
add_theme_support( 'custom-header',
array(
'default-image' => get_template_directory_uri() . '/assets/img/hdr_earth.jpg',
'default-text-color' => '#e2f0d6',
'header-text' => true,
'uploads' => true,
'width' => 1140,
'height' => 200,
'wp-head-callback' => 'wpfw_style_header',
)
);
} // end wpfw_custom_header()
} // end if
// Hook into the 'after_setup_theme' action
add_action( 'after_setup_theme', 'wpfw_custom_header', 11 );
/**
* ----------------------------------------------
* Callback function for updating header styles
* ----------------------------------------------
*/
if ( ! function_exists( 'wpfw_style_header' ) ) {
function wpfw_style_header() {
$text_color = get_header_textcolor();
?>
<style type="text/css" id="wpfw-custom-header-styles">
.site-title a.site-title-link {
color: #<?php echo esc_attr( $text_color ); ?>;
}
<?php if ( display_header_text() != true ) : ?>
.site-title {
display: none;
}
<?php endif; ?>
</style>
<?php
} // end wpfw_style_header()
} // end if...
</code></pre>
|
[
{
"answer_id": 196485,
"author": "dewd",
"author_id": 73424,
"author_profile": "https://wordpress.stackexchange.com/users/73424",
"pm_score": 0,
"selected": false,
"text": "<p>Try this where you need to get the url of the header image and you have set the default:</p>\n\n<pre><code> $url = has_header_image() ? get_header_image() : get_theme_support( 'custom-header', 'default-image' );\n</code></pre>\n"
},
{
"answer_id": 248637,
"author": "Mark",
"author_id": 19396,
"author_profile": "https://wordpress.stackexchange.com/users/19396",
"pm_score": 2,
"selected": true,
"text": "<p>You should register the default headers using <code>register_defaults_headers</code> - e.g.</p>\n\n<pre><code>register_default_headers( array(\n 'default-image' => array(\n 'url' => get_stylesheet_directory_uri() . '/assets/img/default-header.jpg',\n 'thumbnail_url' => get_stylesheet_directory_uri() . '/assets/img/default-header.jpg',\n 'description' => __( 'Default Header Image', 'textdomain' )\n ),\n) );\n</code></pre>\n\n<p>See the codex entry for more info on the function - <a href=\"https://codex.wordpress.org/Function_Reference/register_default_headers\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_default_headers</a>.</p>\n\n<p>The Codex isn't clear, but this function is actually required for <code>custom_headers</code> to function correctly.</p>\n"
},
{
"answer_id": 264598,
"author": "CompactCode",
"author_id": 118063,
"author_profile": "https://wordpress.stackexchange.com/users/118063",
"pm_score": 1,
"selected": false,
"text": "<p>To be honnest i have a working header image in my customizer using the following code :</p>\n\n<p><strong>Functions.php</strong></p>\n\n<pre><code>/* custom header image */\n$headerimage = array(\n 'default-image' => '%s/images/image1.jpg',\n 'width' => 1920,\n 'height' => 1080,\n 'flex-height' => false,\n 'flex-width' => true,\n 'uploads' => true,\n 'random-default' => false,\n 'header-text' => true,\n 'default-text-color' => '',\n 'wp-head-callback' => '',\n 'admin-head-callback' => '',\n 'admin-preview-callback' => '',\n);\nadd_theme_support('custom-header', $headerimage);\n</code></pre>\n\n<p>Nothing in <strong>customizer.php</strong></p>\n\n<p><strong>Where i call the header-image :</strong></p>\n\n<pre><code><header class=\"site-header\">\n <div class=\"row header-home no-gutters\" <?php echo 'style=\"background-image:url(' . get_header_image() . ');' . 'background-repeat: no-repeat;\n background-position: center; background-size: cover;min-height:100vh\">'; ?>\n </div>\n</header>\n</code></pre>\n\n<p><strong>Register default images</strong> (appearently this is needed ALSO functions.php)</p>\n\n<pre><code>register_default_headers( array(\n 'headerimage' => array(\n 'url' => '%s/images/image1.jpg',\n 'thumbnail_url' => '%s/images/image1.jpg',\n 'description' => __( 'headerimage', 'DesignitMultistore' )\n ),\n ) );\n</code></pre>\n"
},
{
"answer_id": 313064,
"author": "Eric van Eldik",
"author_id": 149777,
"author_profile": "https://wordpress.stackexchange.com/users/149777",
"pm_score": 0,
"selected": false,
"text": "<p>For people still having problems, the complete code you need is:</p>\n\n<p>in your functions.php:</p>\n\n<pre><code>register_default_headers( array(\n 'default-image' => array(\n 'url' => get_template_directory_uri() . '/img/header.jpg',\n 'thumbnail_url' => get_template_directory_uri() . '/img/header.jpg',\n 'description' => __( 'Default Header Image', 'textdomain' )\n ),\n) );\n\nfunction yourtheme_custom_header_setup() {\n $args = array(\n 'default-image' => get_template_directory_uri() . '/img/header.jpg',\n 'default-text-color' => '000',\n 'width' => 1200,\n 'height' => 720,\n 'flex-width' => true,\n 'flex-height' => true,\n );\n add_theme_support( 'custom-header', $args );\n}\nadd_action( 'after_setup_theme', 'yourtheme_custom_header_setup' );\n</code></pre>\n\n<p>In your template file (probally header.php):</p>\n\n<pre><code>echo(has_header_image() ? get_header_image() : get_theme_support( 'custom-header', 'default-image' ));\n</code></pre>\n"
}
] |
2015/07/26
|
[
"https://wordpress.stackexchange.com/questions/195641",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12116/"
] |
**Clarification**: My default header image will not **RE-display** (by clicking suggested image) after it has been removed using theme customizer "Hide Image" option.
1. I added theme support for Custom Header Image
```
// Add Theme Support for Custom Header Image
add_theme_support( 'custom-header',
array(
'default-image' => get_template_directory_uri() . '/assets/img/hdr_earth.jpg',
'default-text-color' => '#e2f0d6',
'header-text' => true,
'uploads' => true,
'width' => 1140,
'height' => 200,
'wp-head-callback' => 'wpfw_style_header',
)
);
```
2. Inside the Theme Customizer I see the (default) image displayed as:
* The "Current Header" box, and
* In the "Suggested" box
3. I deleted the current header image by clicking the "Hide Image" button.
**And this is where the problem started**
When I attempt to **re-add the default image** by clicking on the "Suggested" (i.e. default) image...
1. The image **is displayed** in the customizer window.
2. But the image **will not save**, so the image does not display on the web page.
A `var_dump( get_header_image() );` returned `false`, so after reading the function in the core, I see this `if ( 'remove-header' == $url ) return false;`.
So a `var_dump( get_theme_mods() )` does indeed show `'header_image' => string 'remove-header' (length=13)`.
???
... now this is after I added the default image back **and** saved.
What am I missing?
The entire script (custom-header.php)
```
if ( ! function_exists( 'wpfw_custom_header' ) ) {
function wpfw_custom_header() {
// Add theme Support for Custom Backgrounds
add_theme_support( 'custom-background',
array(
'default-color' => '#e2f0d6',
'default-image' => get_template_directory_uri() . '/assets/img/bgp-128x180.jpg',
)
);
// Add Theme Support for Custom Header Image
add_theme_support( 'custom-header',
array(
'default-image' => get_template_directory_uri() . '/assets/img/hdr_earth.jpg',
'default-text-color' => '#e2f0d6',
'header-text' => true,
'uploads' => true,
'width' => 1140,
'height' => 200,
'wp-head-callback' => 'wpfw_style_header',
)
);
} // end wpfw_custom_header()
} // end if
// Hook into the 'after_setup_theme' action
add_action( 'after_setup_theme', 'wpfw_custom_header', 11 );
/**
* ----------------------------------------------
* Callback function for updating header styles
* ----------------------------------------------
*/
if ( ! function_exists( 'wpfw_style_header' ) ) {
function wpfw_style_header() {
$text_color = get_header_textcolor();
?>
<style type="text/css" id="wpfw-custom-header-styles">
.site-title a.site-title-link {
color: #<?php echo esc_attr( $text_color ); ?>;
}
<?php if ( display_header_text() != true ) : ?>
.site-title {
display: none;
}
<?php endif; ?>
</style>
<?php
} // end wpfw_style_header()
} // end if...
```
|
You should register the default headers using `register_defaults_headers` - e.g.
```
register_default_headers( array(
'default-image' => array(
'url' => get_stylesheet_directory_uri() . '/assets/img/default-header.jpg',
'thumbnail_url' => get_stylesheet_directory_uri() . '/assets/img/default-header.jpg',
'description' => __( 'Default Header Image', 'textdomain' )
),
) );
```
See the codex entry for more info on the function - <https://codex.wordpress.org/Function_Reference/register_default_headers>.
The Codex isn't clear, but this function is actually required for `custom_headers` to function correctly.
|
195,665 |
<p>This is on Vanilla installation. I've made a shortcode:-</p>
<pre><code>/**
* Creates a shortcode for shortcode_use_here
* @author Omar Tariq <[email protected]>
*/
function callback_banana_abc( $args ){
/* Don't echo! Always return */
return 'yay!';
}
add_shortcode( 'banana_abc', 'callback_banana_abc' );
</code></pre>
<p>And I've made a template that looks like this:-</p>
<pre><code><?php
/*
* Template Name: Test Template
* Description: Hello world.
*/
$str = '<a href="#" title="[banana_abc]" data-abc="[banana_abc]">[banana_abc]</a>';
echo do_shortcode($str);
</code></pre>
<p>The output is:-</p>
<pre><code><a href="#" title="yay!" data-abc="[banana_abc]">yay!</a>
</code></pre>
<p>This is only for data-* attributes. It works fine when used in <code>title</code> attribute.</p>
|
[
{
"answer_id": 195666,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 0,
"selected": false,
"text": "<p>I cannot reproduce your problem but the way you are using the shortcode to construct small pieces of that string is making me crazy. Try this, and maybe it will work around your problem as well:</p>\n\n<pre><code>function callback_banana_abc( $args ){\n $atts = shortcode_atts( \n array(\n 'title' => 'yay!',\n 'data' => 'yay!',\n 'linktext' => 'yay!'\n ), \n $args\n );\n $str = '<a href=\"#\" title=\"'.$atts['title'].'\" data-abc=\"'.$atts['data'].'\">'.$atts['linktext'].'</a>';\n return $str; \n}\nadd_shortcode( 'banana_abc', 'callback_banana_abc' );\n\n$str = '[banana_abc]';\necho do_shortcode($str);\n\n$str = '[banana_abc title=\"ba\" data=\"na\" linktext=\"na\"]';\necho do_shortcode($str);\n</code></pre>\n"
},
{
"answer_id": 195673,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 4,
"selected": true,
"text": "<p><code>do_shortcodes_in_html_tags()</code> runs attributes through <code>wp_kses_one_attr()</code> which checks them against <code>wp_kses_allowed_html( 'post' )</code> which by default only accepts standard non-data attributes, so you'd have to add your attribute:</p>\n\n<pre><code>add_filter( 'wp_kses_allowed_html', function ( $allowedposttags, $context ) {\n if ( $context == 'post' ) {\n $allowedposttags['a']['data-abc'] = 1;\n }\n return $allowedposttags;\n}, 10, 2 );\n</code></pre>\n"
}
] |
2015/07/27
|
[
"https://wordpress.stackexchange.com/questions/195665",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/36718/"
] |
This is on Vanilla installation. I've made a shortcode:-
```
/**
* Creates a shortcode for shortcode_use_here
* @author Omar Tariq <[email protected]>
*/
function callback_banana_abc( $args ){
/* Don't echo! Always return */
return 'yay!';
}
add_shortcode( 'banana_abc', 'callback_banana_abc' );
```
And I've made a template that looks like this:-
```
<?php
/*
* Template Name: Test Template
* Description: Hello world.
*/
$str = '<a href="#" title="[banana_abc]" data-abc="[banana_abc]">[banana_abc]</a>';
echo do_shortcode($str);
```
The output is:-
```
<a href="#" title="yay!" data-abc="[banana_abc]">yay!</a>
```
This is only for data-\* attributes. It works fine when used in `title` attribute.
|
`do_shortcodes_in_html_tags()` runs attributes through `wp_kses_one_attr()` which checks them against `wp_kses_allowed_html( 'post' )` which by default only accepts standard non-data attributes, so you'd have to add your attribute:
```
add_filter( 'wp_kses_allowed_html', function ( $allowedposttags, $context ) {
if ( $context == 'post' ) {
$allowedposttags['a']['data-abc'] = 1;
}
return $allowedposttags;
}, 10, 2 );
```
|
195,682 |
<p>I have <code>nav_menu_options</code> in my Wordpress database as below.</p>
<pre><code>284,'nav_menu_options','a:2:{i:0;b:0;s:8:\"auto_add\";a:0:{}}'
</code></pre>
<p>I tried to deserialize this value but the result is empty string - I put a code snippet in <code><my theme>/function.php</code> as below</p>
<pre><code>echo 'TRY #1'.'<br>';
$v = 'a:2:{i:0;b:0;s:8:\"auto_add\";a:0:{}}';
$d = unserialize($v);
print_r($d);
echo 'TRY #1 end'.'<br>';
echo 'TRY #2'.'<br>';
$v ='a:5:{s:9:"engine_id";a:1:{i:0;s:9:"300000225";}s:15:"transmission_id";a:1:{i:0;s:6:"257691";}s:5:"plant";a:1:{i:0;s:23:"Oshawa, Ontario, Canada";}s:15:"Manufactured in";a:1:{i:0;s:6:"CANADA";}s:22:"Production Seq. Number";a:1:{i:0;s:6:"151411";}}';
$d = unserialize($v);
print_r($d);
echo 'TRY #2 end'.'<br>';
</code></pre>
<p>The outcome of the above code is as below.</p>
<p>@1 the deserialized Worpdress value results as empty.</p>
<p>@2 a sample valid serialized value results as readable array.</p>
<p><a href="https://i.stack.imgur.com/wuNjx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wuNjx.png" alt="enter image description here"></a></p>
<p>So my question is <strong>Why can't we deserialize Wordpress serialized values?</strong> - this is also posted on wordpress.org <a href="https://wordpress.org/support/topic/cannot-unserialize-wordpress-serialized-values-in-wp_options-table?replies=1#post-7225968" rel="nofollow noreferrer">here</a>.</p>
<p>p.s.</p>
<p>1) More study on Wordpress code shows that we can "decode" the discussed value by using <code>get_option('nav_menu_options');</code> command.</p>
<p>2) The value of <code>nav_menu_options</code> is the real data copied from database</p>
<p><a href="https://i.stack.imgur.com/McaRW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/McaRW.png" alt="enter image description here"></a></p>
|
[
{
"answer_id": 195716,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 4,
"selected": true,
"text": "<p>Your problem is that serialized strings contains escape slashes that are not evaluated as such, because the <em>wrapping</em> quote is a single quote.</p>\n\n<p>You are using:</p>\n\n<pre><code>$v = 'a:2:{i:0;b:0;s:8:\\\"auto_add\\\";a:0:{}}'; // wrong\n</code></pre>\n\n<p>You have to use either</p>\n\n<pre><code>$v = \"a:2:{i:0;b:0;s:8:\\\"auto_add\\\";a:0:{}}\"; // ok\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$v = 'a:2:{i:0;b:0;s:8:\"auto_add\";a:0:{}}'; // ok\n</code></pre>\n\n<p>By the way, you should never <em>manually</em> unserialize values in WordPress database.</p>\n\n<p>When you need to get an option (or a metadata, or anything that may be serialized) use WP functions: they unserialize the value when needed.</p>\n\n<p>E.g. for options, use <a href=\"https://developer.wordpress.org/reference/functions/get_option/\" rel=\"noreferrer\"><code>get_option</code></a>.</p>\n\n<p>If you are interested in how WordPress do unserialization see <a href=\"https://developer.wordpress.org/reference/functions/maybe_unserialize/\" rel=\"noreferrer\"><code>maybe_unserialize</code></a>\n and <a href=\"https://developer.wordpress.org/reference/functions/is_serialized/\" rel=\"noreferrer\"><code>is_serialized</code></a>.</p>\n"
},
{
"answer_id": 410921,
"author": "Muhammad Tanweer",
"author_id": 227118,
"author_profile": "https://wordpress.stackexchange.com/users/227118",
"pm_score": 0,
"selected": false,
"text": "<p>Its a very old issue but I recently faced similar issue. I was using the multi image upload plugin <a href=\"https://wordpress.org/plugins/multi-image-upload/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/multi-image-upload/</a> and I had Godaddy backups setup. I recently needed to restore my website from godaddy using its backup. and all of a sudden the serialized images data that multi image upload stored in post meta, the unserialize wasn't working on that.\nAfter banging my head around it for almost 2 days, I found that instead of using the "Restore" function to restore db, i needed to downloaded the sql backup, and through phpmyadmin import it and all went well.\nSeems like the restore function was corrupting the serialized data.\nMay help someone.</p>\n"
}
] |
2015/07/27
|
[
"https://wordpress.stackexchange.com/questions/195682",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/992/"
] |
I have `nav_menu_options` in my Wordpress database as below.
```
284,'nav_menu_options','a:2:{i:0;b:0;s:8:\"auto_add\";a:0:{}}'
```
I tried to deserialize this value but the result is empty string - I put a code snippet in `<my theme>/function.php` as below
```
echo 'TRY #1'.'<br>';
$v = 'a:2:{i:0;b:0;s:8:\"auto_add\";a:0:{}}';
$d = unserialize($v);
print_r($d);
echo 'TRY #1 end'.'<br>';
echo 'TRY #2'.'<br>';
$v ='a:5:{s:9:"engine_id";a:1:{i:0;s:9:"300000225";}s:15:"transmission_id";a:1:{i:0;s:6:"257691";}s:5:"plant";a:1:{i:0;s:23:"Oshawa, Ontario, Canada";}s:15:"Manufactured in";a:1:{i:0;s:6:"CANADA";}s:22:"Production Seq. Number";a:1:{i:0;s:6:"151411";}}';
$d = unserialize($v);
print_r($d);
echo 'TRY #2 end'.'<br>';
```
The outcome of the above code is as below.
@1 the deserialized Worpdress value results as empty.
@2 a sample valid serialized value results as readable array.
[](https://i.stack.imgur.com/wuNjx.png)
So my question is **Why can't we deserialize Wordpress serialized values?** - this is also posted on wordpress.org [here](https://wordpress.org/support/topic/cannot-unserialize-wordpress-serialized-values-in-wp_options-table?replies=1#post-7225968).
p.s.
1) More study on Wordpress code shows that we can "decode" the discussed value by using `get_option('nav_menu_options');` command.
2) The value of `nav_menu_options` is the real data copied from database
[](https://i.stack.imgur.com/McaRW.png)
|
Your problem is that serialized strings contains escape slashes that are not evaluated as such, because the *wrapping* quote is a single quote.
You are using:
```
$v = 'a:2:{i:0;b:0;s:8:\"auto_add\";a:0:{}}'; // wrong
```
You have to use either
```
$v = "a:2:{i:0;b:0;s:8:\"auto_add\";a:0:{}}"; // ok
```
or
```
$v = 'a:2:{i:0;b:0;s:8:"auto_add";a:0:{}}'; // ok
```
By the way, you should never *manually* unserialize values in WordPress database.
When you need to get an option (or a metadata, or anything that may be serialized) use WP functions: they unserialize the value when needed.
E.g. for options, use [`get_option`](https://developer.wordpress.org/reference/functions/get_option/).
If you are interested in how WordPress do unserialization see [`maybe_unserialize`](https://developer.wordpress.org/reference/functions/maybe_unserialize/)
and [`is_serialized`](https://developer.wordpress.org/reference/functions/is_serialized/).
|
195,688 |
<p>I've written a code in a WP_Query to converting a string (the_content) to an array (choices). But it seems wrong! In fact, the choices array is empty after each loop. However str string is notnull. How can i handle this array to be nutnull?
Any help would be appreciated.</p>
<pre><code>$first_query = new WP_Query( $args );
while ($first_query->have_posts()) : $first_query->the_post();
the_title(); //echo the title
the_content(); //echo the content
$str = the_content();
$choices = explode("-",$str);
var_dump($choices);
endwhile;
</code></pre>
|
[
{
"answer_id": 195690,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>You have a couple of issues here</p>\n\n<ul>\n<li><p><code>the_content()</code> echos the content to screen. You should be using <code>get_the_content()</code> which returns the content. Just remember, <code>get_the_content()</code> is unfiltered, so if you need filtered content, use <code>apply_filters( 'the_content', get_the_content() )</code> which will return filtered content.</p></li>\n<li><p>Your <code>explode()</code> function is probably wrong as well. You are using a hyphen to explode your content into pieces of an array. If your content don't contain hyphens, your array will only have one key with the complete content as value. You would probably need to use white spaces (<em><code>explode( ' ', get_the_content() );</code></em>) or regular expressions or something similar to targt more than hypens or white spaces to explode the content. In one of my <a href=\"https://wordpress.stackexchange.com/a/141136/31545\">previous posts for custom excerpts</a> , I have used something similar to explode my content, here is something you can try and experiment with</p>\n\n<pre><code>preg_match_all('/(<[^>]+>|[^<>\\s]+)\\s*/u', get_the_content(), $tokens);\nvar_dump( $tokens );\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 195694,
"author": "Ulugov",
"author_id": 44914,
"author_profile": "https://wordpress.stackexchange.com/users/44914",
"pm_score": 0,
"selected": false,
"text": "<p>Try with: <code>$str = get_the_content();</code></p>\n"
}
] |
2015/07/27
|
[
"https://wordpress.stackexchange.com/questions/195688",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71448/"
] |
I've written a code in a WP\_Query to converting a string (the\_content) to an array (choices). But it seems wrong! In fact, the choices array is empty after each loop. However str string is notnull. How can i handle this array to be nutnull?
Any help would be appreciated.
```
$first_query = new WP_Query( $args );
while ($first_query->have_posts()) : $first_query->the_post();
the_title(); //echo the title
the_content(); //echo the content
$str = the_content();
$choices = explode("-",$str);
var_dump($choices);
endwhile;
```
|
You have a couple of issues here
* `the_content()` echos the content to screen. You should be using `get_the_content()` which returns the content. Just remember, `get_the_content()` is unfiltered, so if you need filtered content, use `apply_filters( 'the_content', get_the_content() )` which will return filtered content.
* Your `explode()` function is probably wrong as well. You are using a hyphen to explode your content into pieces of an array. If your content don't contain hyphens, your array will only have one key with the complete content as value. You would probably need to use white spaces (*`explode( ' ', get_the_content() );`*) or regular expressions or something similar to targt more than hypens or white spaces to explode the content. In one of my [previous posts for custom excerpts](https://wordpress.stackexchange.com/a/141136/31545) , I have used something similar to explode my content, here is something you can try and experiment with
```
preg_match_all('/(<[^>]+>|[^<>\s]+)\s*/u', get_the_content(), $tokens);
var_dump( $tokens );
```
|
195,736 |
<p>I want to work with html form but i cant understand the Action method and when we need to use it.
For example found this code on w3schools:</p>
<pre><code><form action="action_page.php">
First name:<br>
<input type="text" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
</code></pre>
<p>how can we use 'lastname' in other file?</p>
|
[
{
"answer_id": 195690,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>You have a couple of issues here</p>\n\n<ul>\n<li><p><code>the_content()</code> echos the content to screen. You should be using <code>get_the_content()</code> which returns the content. Just remember, <code>get_the_content()</code> is unfiltered, so if you need filtered content, use <code>apply_filters( 'the_content', get_the_content() )</code> which will return filtered content.</p></li>\n<li><p>Your <code>explode()</code> function is probably wrong as well. You are using a hyphen to explode your content into pieces of an array. If your content don't contain hyphens, your array will only have one key with the complete content as value. You would probably need to use white spaces (<em><code>explode( ' ', get_the_content() );</code></em>) or regular expressions or something similar to targt more than hypens or white spaces to explode the content. In one of my <a href=\"https://wordpress.stackexchange.com/a/141136/31545\">previous posts for custom excerpts</a> , I have used something similar to explode my content, here is something you can try and experiment with</p>\n\n<pre><code>preg_match_all('/(<[^>]+>|[^<>\\s]+)\\s*/u', get_the_content(), $tokens);\nvar_dump( $tokens );\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 195694,
"author": "Ulugov",
"author_id": 44914,
"author_profile": "https://wordpress.stackexchange.com/users/44914",
"pm_score": 0,
"selected": false,
"text": "<p>Try with: <code>$str = get_the_content();</code></p>\n"
}
] |
2015/07/27
|
[
"https://wordpress.stackexchange.com/questions/195736",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71455/"
] |
I want to work with html form but i cant understand the Action method and when we need to use it.
For example found this code on w3schools:
```
<form action="action_page.php">
First name:<br>
<input type="text" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
```
how can we use 'lastname' in other file?
|
You have a couple of issues here
* `the_content()` echos the content to screen. You should be using `get_the_content()` which returns the content. Just remember, `get_the_content()` is unfiltered, so if you need filtered content, use `apply_filters( 'the_content', get_the_content() )` which will return filtered content.
* Your `explode()` function is probably wrong as well. You are using a hyphen to explode your content into pieces of an array. If your content don't contain hyphens, your array will only have one key with the complete content as value. You would probably need to use white spaces (*`explode( ' ', get_the_content() );`*) or regular expressions or something similar to targt more than hypens or white spaces to explode the content. In one of my [previous posts for custom excerpts](https://wordpress.stackexchange.com/a/141136/31545) , I have used something similar to explode my content, here is something you can try and experiment with
```
preg_match_all('/(<[^>]+>|[^<>\s]+)\s*/u', get_the_content(), $tokens);
var_dump( $tokens );
```
|
195,743 |
<p>I am sturggling with how authentication works in my scenario.</p>
<p>I have Wordpress site which provides set of custom APIs secured behind <code>oAuth2 Authentication</code> using <a href="https://wordpress.org/plugins/oauth2-provider/" rel="nofollow">Wp OAuth Server</a> plugin. </p>
<p>I started with building simple custom endpoint by extending <a href="https://wordpress.org/plugins/json-rest-api/" rel="nofollow">WP REST API (WP API)</a> plugin. I setup up my endpoint as POST <code>/api/v1/projects</code>, where my callback function is even more simple,</p>
<pre><code>function create_projects() {
// my code to create new project
return ['code'=>201, 'message'=>'project created'];
}
</code></pre>
<p>So far so good. This API is available and I can get the list of projects using POSTMAN Chrome Extension.</p>
<p>The part where I am having issues is to implement authentication. So only authenticated users are able to comsume this api. How can I setup authentication and which authentication will suit me in this scenario where my wordpress site is hosting the projects and only authenticated users will be able to create new projects on my site using the API i provided as above.</p>
<p>Can someone please point me to right direction?</p>
<p><strong>Update#1</strong></p>
<p>I have manage to implement oAuth2 Authentication and will answer my question when I have a time. In case you are interesting in knowing how to do it, drop me a comment</p>
|
[
{
"answer_id": 198867,
"author": "Justin P Greer",
"author_id": 77908,
"author_profile": "https://wordpress.stackexchange.com/users/77908",
"pm_score": 1,
"selected": false,
"text": "<p>You will have to follow the details from the developers website located <a href=\"https://wp-oauth.com/knowledge-base/authenticating-with-wp-rest-api/\" rel=\"nofollow\">here</a>. (FYI, I am one lead on the project). Basically, what is boils down to, is that you are going to create a client in WP OAuth Server and give the details to your authenticated users. Your users would then setup using the grant type of \"password\" (user credentials). This is not ideal but will get you to a place your can expand the framework. </p>\n\n<p>If you feel like getting your hands dirty, you can add a custom meta field to your user accounts that will say if they are allowed to access the data or not. Then, every time a user authenticates, you can either allow them access to WP OAuth Server or block access based on if their account has the correct meta value or not.</p>\n"
},
{
"answer_id": 353606,
"author": "ana",
"author_id": 179101,
"author_profile": "https://wordpress.stackexchange.com/users/179101",
"pm_score": 0,
"selected": false,
"text": "<p>I am using this plugin <a href=\"https://garazlab.com/product/wp-oauth-sso-multiple-wordpress-user-sync/\" rel=\"nofollow noreferrer\">https://garazlab.com/product/wp-oauth-sso-multiple-wordpress-user-sync/</a> for oauth2 and SSO. you can try it also.</p>\n"
}
] |
2015/07/27
|
[
"https://wordpress.stackexchange.com/questions/195743",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22857/"
] |
I am sturggling with how authentication works in my scenario.
I have Wordpress site which provides set of custom APIs secured behind `oAuth2 Authentication` using [Wp OAuth Server](https://wordpress.org/plugins/oauth2-provider/) plugin.
I started with building simple custom endpoint by extending [WP REST API (WP API)](https://wordpress.org/plugins/json-rest-api/) plugin. I setup up my endpoint as POST `/api/v1/projects`, where my callback function is even more simple,
```
function create_projects() {
// my code to create new project
return ['code'=>201, 'message'=>'project created'];
}
```
So far so good. This API is available and I can get the list of projects using POSTMAN Chrome Extension.
The part where I am having issues is to implement authentication. So only authenticated users are able to comsume this api. How can I setup authentication and which authentication will suit me in this scenario where my wordpress site is hosting the projects and only authenticated users will be able to create new projects on my site using the API i provided as above.
Can someone please point me to right direction?
**Update#1**
I have manage to implement oAuth2 Authentication and will answer my question when I have a time. In case you are interesting in knowing how to do it, drop me a comment
|
You will have to follow the details from the developers website located [here](https://wp-oauth.com/knowledge-base/authenticating-with-wp-rest-api/). (FYI, I am one lead on the project). Basically, what is boils down to, is that you are going to create a client in WP OAuth Server and give the details to your authenticated users. Your users would then setup using the grant type of "password" (user credentials). This is not ideal but will get you to a place your can expand the framework.
If you feel like getting your hands dirty, you can add a custom meta field to your user accounts that will say if they are allowed to access the data or not. Then, every time a user authenticates, you can either allow them access to WP OAuth Server or block access based on if their account has the correct meta value or not.
|
195,753 |
<p>I've got a 'downloads' custom post, with his custom taxonomy. The taxonomy has 2 main terms. One of the 2, has 4 sub-terms. I'm currently using the wp templating system to get a standard wpquery of the parent term into a <code>taxonomy-taxonomyname-termname.php</code> page. Till here, all fine.</p>
<p>Now what I'd like to do is to show all the posts under the parent term, without pagination (this is not a problem). But I would like show them splitted/grouped by sub-terms (with the sub-term name above each of the 4 sub-terms groups).</p>
<p>Normally, I would perform a custom query. But since this time I'm trying to take advantage of the default wp query system, I'd like to use just the loop. Is there a way to have the posts grouped by sub-term?</p>
|
[
{
"answer_id": 195757,
"author": "Mike",
"author_id": 45704,
"author_profile": "https://wordpress.stackexchange.com/users/45704",
"pm_score": 2,
"selected": false,
"text": "<p>If I understand the question correctly, you want to produce something like this:</p>\n\n<h3>Sub-Item 1</h3>\n\n<p>Post 1</p>\n\n<p>Post 2</p>\n\n<p>[...]</p>\n\n<h3>Sub Item 2</h3>\n\n<p>Post 1</p>\n\n<p>Post 2</p>\n\n<p>[...]</p>\n\n<p>There may be a more efficient way than what I am about to tell you, but I would try something like this:</p>\n\n<h3>First create an array to hold your sorted posts.</h3>\n\n<pre><code>$sortedPosts = array();\n</code></pre>\n\n<h3>Next, create an array for each of your sub-terms.</h3>\n\n<pre><code>foreach ($subTerms as $subTerm) {\n $sortedPosts[$subTerm] = array();\n}\n</code></pre>\n\n<h3>Loop through the posts in your query, and sort them based on the assigned term.</h3>\n\n<pre><code>if (have_posts()) {\n while (have_posts()) {\n the_post();\n $postTerms = get_terms('taxonomyName', array('fields' => 'name'));\n\n if (is_array($postTerms)) {\n foreach ($subTerms as $subTerm) {\n if (in_array($subTerm, $postTerms)) {\n global $post;\n\n $sortedPosts[$subTerm][] = $post;\n /* This grabs the array stored at $sortedPosts[$subTerm]\n and then inserts the current post at the end of it. */\n }\n }\n }\n }\n}\n</code></pre>\n\n<h3>Once all the posts have been sorted, loop through your sorted array to print the display.</h3>\n\n<pre><code>foreach ($subTerms as $subTerm) {\n $myPosts = $sortedPosts[$subTerm];\n\n echo '<h1>' . $subTerm . '</h1>';\n\n foreach ($myPosts as $currentPost) {\n global $post;\n $post = $currentPost;\n\n // Enter post display stuff here\n }\n\n echo '<hr>'\n}\n</code></pre>\n"
},
{
"answer_id": 195764,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>Always great if someone wants to use better, more correct and more efficient ways to get things done. To achieve what you need is not difficult. </p>\n\n<h2>WORKSFLOW:</h2>\n\n<ul>\n<li><p>Use the <code>usort()</code> to create your custom sort order</p></li>\n<li><p>Use the <code>the_posts</code> filter to sort and return the sorted array of posts just before the loop is executed</p></li>\n<li><p>Inside the loop, all you need to do is to compare the previous post and current post terms and act on that</p></li>\n</ul>\n\n<h2>THE CODE:</h2>\n\n<p>Lets look at the code:</p>\n\n<p>First, get the sorting done using <code>usort()</code> and <code>the_posts</code> filter: (<em>Requires at least PHP 5.4+. If you don't have at least PHP 5.4, then you are sure to run into security issues. Also note, all the code is untested and might be buggy</em>)</p>\n\n<pre><code>add_filter( 'the_posts', function ( $posts, $q )\n{\n if ( $q->is_main_query() // Target the main query only\n && $q->is_tax() // Change to target only specific term or taxonomy\n ) {\n /**\n * We will now sort the $posts array before the loop executes. We will use usort()\n *\n * There is a bug in usort causing the following error:\n * usort(): Array was modified by the user comparison function\n * @see https://bugs.php.net/bug.php?id=50688\n * This bug has yet to be fixed, when, no one knows. The only workaround is to suppress the error reporting\n * by using the @ sign before usort\n */\n @usort( $posts, function ( $a, $b )\n {\n /**\n * Get the respective terms from the posts \n * We will use the first term's name\n */\n $array_a = get_the_terms( $a->ID, 'TAXONOMY_NAME_HERE' )[0]->name;\n $array_b = get_the_terms( $b->ID, 'TAXONOMY_NAME_HERE' )[0]->name;\n\n // Sort by term name, if they are the same, sort by post date\n if ( $array_a != $array_b ) {\n return strcasecmp( $array_a, $array_b ); // Sort terms alphabetically, ascending\n // return strcasecmp( $array_b, $array_a ); // Sort terms alphabetically, descending\n } else {\n return $a < $b; // Sort by date if terms are the same. Change < to > if the post date order is incorrect\n }\n }\n }\n}, 10, 2 );\n</code></pre>\n\n<p>This should take care of the sorting. As I have stated, just make sure the date sorting is correct within the terms. If not, just change <code><</code> to <code>></code></p>\n\n<p>Now we can display the term names inside the loop. Adjust and modify as needed</p>\n\n<pre><code>if ( have_posts() ) {\n // Define variable to hold previous post term name\n $term_string = '';\n while ( have_posts() ) {\n the_post();\n global $post;\n // Get the post terms. Use the first term's name\n $term_name = get_the_terms( $post->ID, 'TAXONOMY_NAME_HERE' )[0]->name;\n // Display the taxonomy name if previous and current post term name don't match\n if ( $term_string != $term_name )\n echo '<h2>' . $term_name . '</h2>'; // Add styling and tags to suite your needs\n\n // Update the $term_string variable\n $term_string = $term_name;\n\n // REST OF YOUR LOOP\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 196081,
"author": "Luca Reghellin",
"author_id": 10381,
"author_profile": "https://wordpress.stackexchange.com/users/10381",
"pm_score": 1,
"selected": true,
"text": "<p>Ok, thank you all for your good answers. Anyway, I need more flexibility, so I ended up not using the wp template auto-sugars... </p>\n\n<p>This answer is therefore not strictly related to my own original question, but I think it can help people too.</p>\n\n<p>I built a custom function that retrieves a set of custom posts form a specific custom taxonomy and an optional parent term. If parent is passed, returned posts will belong to direct parent term children. This is the code:</p>\n\n<pre><code>// $post_type: string\n // $taxonomy: string\n // $parent_term: string (slug) || int (term_id)\n // retrieves posts of a specific post_type and taxonomy, sorted by term\n function get_taxonomy_posts($post_type, $taxonomy, $parent_term = ''){\n\n if(!$post_type || !$taxonomy) return false;\n\n global $wpdb;\n\n //if $parent_term is defined and is not an integer then should be a slug, so let's get its id\n if(!empty($parent_term) && !is_int($parent_term)){\n $parent_data = get_term_by('slug',$parent_term,$taxonomy);\n $parent_term = $parent_data->term_id;\n }\n\n $term_ids = get_terms($taxonomy, array( 'parent' => $parent_term, 'fields' => 'ids' ));\n if(is_wp_error($term_ids)) return false;\n\n $term_ids_str = implode(',',$term_ids);\n\n // NOTE: terms.term_order gets added to tables by this plugin:\n // http://wordpress.org/plugins/taxonomy-terms-order/\n $query = $wpdb->prepare(\n \"select p.ID, p.post_title, p.post_content, p.post_excerpt, t.term_id, t.term_order, t.name as term_name, t.slug as term_slug, tt.count\n from \" . $wpdb->prefix . \"posts p\n inner join \" . $wpdb->prefix . \"term_relationships rel on p.ID = rel.object_id\n inner join \" . $wpdb->prefix . \"term_taxonomy tt on tt.term_taxonomy_id = rel.term_taxonomy_id\n inner join \" . $wpdb->prefix . \"terms t on tt.term_id = t.term_id\n where p.post_type = %s and p.post_status = %s and t.term_id in (\" . $term_ids_str . \")\n order by t.term_order, p.menu_order\"\n ,$post_type\n ,\"publish\"\n );\n\n $records = $wpdb->get_results($query);\n $posts_array = array();\n\n foreach($records as $record){\n $term_name = $record->term_name;\n if(!key_exists($term_name, $posts_array)) $posts_array[$term_name] = array();\n $posts_array[$term_name][] = $record;\n }\n\n return $posts_array;\n\n }//end get taxonomy_posts \n</code></pre>\n\n<p>It will give you an array where keys are term names and values are arrays of posts (or more precisely, post data of posts) belonging to that term. It can be easily modified to have for example keys as term_id instead of term_name. The single post data returned is like this:</p>\n\n<pre><code> object(stdClass)#2308 (9) {\n [\"ID\"]=>\n string(3) \"269\"\n [\"post_title\"]=>\n string(26) \"title\"\n [\"post_content\"]=>\n string(0) \"content\"\n [\"post_excerpt\"]=>\n string(0) \"excerpt\"\n [\"term_id\"]=>\n string(3) \"803\"\n [\"term_order\"]=>\n string(1) \"2\"\n [\"term_name\"]=>\n string(27) \"term name\"\n [\"term_slug\"]=>\n string(26) \"term-slug\"\n [\"count\"]=>\n string(1) \"3\"\n }\n</code></pre>\n\n<p>SIDE NOTE 1: currently, I'm using the taxonomy-terms-order plugins and so in the query I'm ordering terms by the custom term_order field. Again, if you don't use the plugin, just change the fields retrieved and order by clause as you prefer.</p>\n\n<p>SIDE NOTE 2: Instead of a taxonomy-taxonomyname-termname.php, now I basically use a dummy page and apply a custom template (I mean <code>/* Template Name: [name] */</code>): this is not mandatory, but I do it to have the wp's main query just do a simple 1 post query instead a sort of duplicated term query.</p>\n\n<p>Hope it helps!</p>\n"
}
] |
2015/07/27
|
[
"https://wordpress.stackexchange.com/questions/195753",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10381/"
] |
I've got a 'downloads' custom post, with his custom taxonomy. The taxonomy has 2 main terms. One of the 2, has 4 sub-terms. I'm currently using the wp templating system to get a standard wpquery of the parent term into a `taxonomy-taxonomyname-termname.php` page. Till here, all fine.
Now what I'd like to do is to show all the posts under the parent term, without pagination (this is not a problem). But I would like show them splitted/grouped by sub-terms (with the sub-term name above each of the 4 sub-terms groups).
Normally, I would perform a custom query. But since this time I'm trying to take advantage of the default wp query system, I'd like to use just the loop. Is there a way to have the posts grouped by sub-term?
|
Ok, thank you all for your good answers. Anyway, I need more flexibility, so I ended up not using the wp template auto-sugars...
This answer is therefore not strictly related to my own original question, but I think it can help people too.
I built a custom function that retrieves a set of custom posts form a specific custom taxonomy and an optional parent term. If parent is passed, returned posts will belong to direct parent term children. This is the code:
```
// $post_type: string
// $taxonomy: string
// $parent_term: string (slug) || int (term_id)
// retrieves posts of a specific post_type and taxonomy, sorted by term
function get_taxonomy_posts($post_type, $taxonomy, $parent_term = ''){
if(!$post_type || !$taxonomy) return false;
global $wpdb;
//if $parent_term is defined and is not an integer then should be a slug, so let's get its id
if(!empty($parent_term) && !is_int($parent_term)){
$parent_data = get_term_by('slug',$parent_term,$taxonomy);
$parent_term = $parent_data->term_id;
}
$term_ids = get_terms($taxonomy, array( 'parent' => $parent_term, 'fields' => 'ids' ));
if(is_wp_error($term_ids)) return false;
$term_ids_str = implode(',',$term_ids);
// NOTE: terms.term_order gets added to tables by this plugin:
// http://wordpress.org/plugins/taxonomy-terms-order/
$query = $wpdb->prepare(
"select p.ID, p.post_title, p.post_content, p.post_excerpt, t.term_id, t.term_order, t.name as term_name, t.slug as term_slug, tt.count
from " . $wpdb->prefix . "posts p
inner join " . $wpdb->prefix . "term_relationships rel on p.ID = rel.object_id
inner join " . $wpdb->prefix . "term_taxonomy tt on tt.term_taxonomy_id = rel.term_taxonomy_id
inner join " . $wpdb->prefix . "terms t on tt.term_id = t.term_id
where p.post_type = %s and p.post_status = %s and t.term_id in (" . $term_ids_str . ")
order by t.term_order, p.menu_order"
,$post_type
,"publish"
);
$records = $wpdb->get_results($query);
$posts_array = array();
foreach($records as $record){
$term_name = $record->term_name;
if(!key_exists($term_name, $posts_array)) $posts_array[$term_name] = array();
$posts_array[$term_name][] = $record;
}
return $posts_array;
}//end get taxonomy_posts
```
It will give you an array where keys are term names and values are arrays of posts (or more precisely, post data of posts) belonging to that term. It can be easily modified to have for example keys as term\_id instead of term\_name. The single post data returned is like this:
```
object(stdClass)#2308 (9) {
["ID"]=>
string(3) "269"
["post_title"]=>
string(26) "title"
["post_content"]=>
string(0) "content"
["post_excerpt"]=>
string(0) "excerpt"
["term_id"]=>
string(3) "803"
["term_order"]=>
string(1) "2"
["term_name"]=>
string(27) "term name"
["term_slug"]=>
string(26) "term-slug"
["count"]=>
string(1) "3"
}
```
SIDE NOTE 1: currently, I'm using the taxonomy-terms-order plugins and so in the query I'm ordering terms by the custom term\_order field. Again, if you don't use the plugin, just change the fields retrieved and order by clause as you prefer.
SIDE NOTE 2: Instead of a taxonomy-taxonomyname-termname.php, now I basically use a dummy page and apply a custom template (I mean `/* Template Name: [name] */`): this is not mandatory, but I do it to have the wp's main query just do a simple 1 post query instead a sort of duplicated term query.
Hope it helps!
|
195,787 |
<p>Can please anyone help? I created custom meta boxes, two of them are in textarea.
This is what i have:</p>
<pre><code>array(
'label'=> 'Ingredients',
'desc' => 'List of ingrediends',
'id' => $prefix.'ingrediends',
'type' => 'textarea'
),
array(
'label'=> 'Directions',
'desc' => 'Directions',
'id' => $prefix.'directions',
'type' => 'textarea'
)
</code></pre>
<p>==========================</p>
<pre><code>case 'textarea':
echo '<textarea name="'.$field['id'].'" id="'.$field['id'].'" cols="60" rows="4">'.$meta.'</textarea>
<br /><span class="description">'.$field['desc'].'</span>';
break;
</code></pre>
<p>How do i add wp_editor? I tried:</p>
<pre><code>wp_editor( $content, 'recipe_directions', array( 'textarea_name' => 'recipe_directions', 'media_buttons' => false, 'tinymce' => array() ) );
</code></pre>
<p>But it doesn't work still showing regular field. Can anyone help.
The whole idea is to make regular textarea like rich text editor</p>
<p>Thanks for your help .... anyone:)</p>
|
[
{
"answer_id": 198115,
"author": "aaron.cimolini",
"author_id": 67495,
"author_profile": "https://wordpress.stackexchange.com/users/67495",
"pm_score": 2,
"selected": false,
"text": "<p>To use wp_editor() you'll need to replace your textarea tag with the output from wp_editor() like so:</p>\n\n<pre><code>case 'textarea':\n wp_editor($meta, $field['id']);\n echo '<br /><span class=\"description\">'.$field['desc'].'</span>';\nbreak; \n</code></pre>\n\n<p>You don't need to echo wp_editor() since it does it automatically. You can pass an array of settings as a 3rd argument to configure it's behaviour. More info here:</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_editor\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_editor</a></p>\n"
},
{
"answer_id": 198218,
"author": "Alex Osipov",
"author_id": 76850,
"author_profile": "https://wordpress.stackexchange.com/users/76850",
"pm_score": 1,
"selected": true,
"text": "<pre><code>case 'textarea':\nwp_editor($meta, $field['id']);\necho '<br /><span class=\"description\">'.$field['desc'].'</span>';\nbreak; \n</code></pre>\n\n<p>This is the way to fix it.</p>\n"
}
] |
2015/07/27
|
[
"https://wordpress.stackexchange.com/questions/195787",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76850/"
] |
Can please anyone help? I created custom meta boxes, two of them are in textarea.
This is what i have:
```
array(
'label'=> 'Ingredients',
'desc' => 'List of ingrediends',
'id' => $prefix.'ingrediends',
'type' => 'textarea'
),
array(
'label'=> 'Directions',
'desc' => 'Directions',
'id' => $prefix.'directions',
'type' => 'textarea'
)
```
==========================
```
case 'textarea':
echo '<textarea name="'.$field['id'].'" id="'.$field['id'].'" cols="60" rows="4">'.$meta.'</textarea>
<br /><span class="description">'.$field['desc'].'</span>';
break;
```
How do i add wp\_editor? I tried:
```
wp_editor( $content, 'recipe_directions', array( 'textarea_name' => 'recipe_directions', 'media_buttons' => false, 'tinymce' => array() ) );
```
But it doesn't work still showing regular field. Can anyone help.
The whole idea is to make regular textarea like rich text editor
Thanks for your help .... anyone:)
|
```
case 'textarea':
wp_editor($meta, $field['id']);
echo '<br /><span class="description">'.$field['desc'].'</span>';
break;
```
This is the way to fix it.
|
195,797 |
<p>I am creating a section on my site that will display the last five categories created. How could I do that?</p>
<p>UPDATE:
The code below is what I want, just like to know how to apply in order, if the latest published categories.</p>
<pre><code><?php
$cat = get_query_var('cat');
$categories=get_categories('child_of='.$cat);
if ($categories) { ?>
<div class="subcat-archive">
<?php
$cat = get_query_var('cat');
$categories=get_categories('child_of='.$cat);
if ($categories) {
foreach($categories as $term) {
echo $title . '<a href="' . get_category_link( $term->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $term->name ) . '" ' . '>' . $term->name.'</a> | '; }
}
?>
</div>
<?php
}
else {
?>
<?php
}
?>
</code></pre>
|
[
{
"answer_id": 195800,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 2,
"selected": false,
"text": "<p>the id of the categories is autoincrement so you can sort by id to find the last one : </p>\n\n<pre><code>$args = array(\n \"type\" => \"post\",\n \"orderby\" => \"id\",\n \"order\" => \"DESC\",\n \"number\" => \"5\",\n \"taxonomy\" => \"category\",\n \"hide_empty\" => FALSE, // TRUE or FALSE depending what you want\n);\n\n$categories = get_categories($args);\n</code></pre>\n"
},
{
"answer_id": 195862,
"author": "prempal sharma",
"author_id": 76877,
"author_profile": "https://wordpress.stackexchange.com/users/76877",
"pm_score": 1,
"selected": false,
"text": "<p>use this code for access categories</p>\n\n<pre><code>$args = new WP_Query( array(\n 'type' = 'post',\n 'taxonomy' = 'taxonomy_name',\n 'order' = 'ASC',\n 'orderby' = 'id'\n));\n//this function are used for access all categories\n$query = get_categories($args);\n</code></pre>\n"
}
] |
2015/07/27
|
[
"https://wordpress.stackexchange.com/questions/195797",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68649/"
] |
I am creating a section on my site that will display the last five categories created. How could I do that?
UPDATE:
The code below is what I want, just like to know how to apply in order, if the latest published categories.
```
<?php
$cat = get_query_var('cat');
$categories=get_categories('child_of='.$cat);
if ($categories) { ?>
<div class="subcat-archive">
<?php
$cat = get_query_var('cat');
$categories=get_categories('child_of='.$cat);
if ($categories) {
foreach($categories as $term) {
echo $title . '<a href="' . get_category_link( $term->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $term->name ) . '" ' . '>' . $term->name.'</a> | '; }
}
?>
</div>
<?php
}
else {
?>
<?php
}
?>
```
|
the id of the categories is autoincrement so you can sort by id to find the last one :
```
$args = array(
"type" => "post",
"orderby" => "id",
"order" => "DESC",
"number" => "5",
"taxonomy" => "category",
"hide_empty" => FALSE, // TRUE or FALSE depending what you want
);
$categories = get_categories($args);
```
|
195,810 |
<p>I have a new website and it's loading extremely slowly. It happens both in admin area and frontend, so I'm guessing is not a plugin or theme issue. In fact, I've tried deactivating all plugins and activating one by one and found no difference. I've tried switching the theme too and it didn't solve the problem.</p>
<p>I have already contacted my hosting company and they told me there is nothing wrong with the server.</p>
<p>The website is <a href="http://www.marylindemuth.com.br" rel="nofollow">http://www.marylindemuth.com.br</a></p>
<p>Do you have any idea of what might be going on? I have another website running in the same server and there are no issues with it.</p>
<p>Thank you!</p>
|
[
{
"answer_id": 195800,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 2,
"selected": false,
"text": "<p>the id of the categories is autoincrement so you can sort by id to find the last one : </p>\n\n<pre><code>$args = array(\n \"type\" => \"post\",\n \"orderby\" => \"id\",\n \"order\" => \"DESC\",\n \"number\" => \"5\",\n \"taxonomy\" => \"category\",\n \"hide_empty\" => FALSE, // TRUE or FALSE depending what you want\n);\n\n$categories = get_categories($args);\n</code></pre>\n"
},
{
"answer_id": 195862,
"author": "prempal sharma",
"author_id": 76877,
"author_profile": "https://wordpress.stackexchange.com/users/76877",
"pm_score": 1,
"selected": false,
"text": "<p>use this code for access categories</p>\n\n<pre><code>$args = new WP_Query( array(\n 'type' = 'post',\n 'taxonomy' = 'taxonomy_name',\n 'order' = 'ASC',\n 'orderby' = 'id'\n));\n//this function are used for access all categories\n$query = get_categories($args);\n</code></pre>\n"
}
] |
2015/07/28
|
[
"https://wordpress.stackexchange.com/questions/195810",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/72739/"
] |
I have a new website and it's loading extremely slowly. It happens both in admin area and frontend, so I'm guessing is not a plugin or theme issue. In fact, I've tried deactivating all plugins and activating one by one and found no difference. I've tried switching the theme too and it didn't solve the problem.
I have already contacted my hosting company and they told me there is nothing wrong with the server.
The website is <http://www.marylindemuth.com.br>
Do you have any idea of what might be going on? I have another website running in the same server and there are no issues with it.
Thank you!
|
the id of the categories is autoincrement so you can sort by id to find the last one :
```
$args = array(
"type" => "post",
"orderby" => "id",
"order" => "DESC",
"number" => "5",
"taxonomy" => "category",
"hide_empty" => FALSE, // TRUE or FALSE depending what you want
);
$categories = get_categories($args);
```
|
195,827 |
<p>I'm trying to test wp_mail() in my local.
When I var dump wp_mail,I get Boolean false.This is my code</p>
<pre><code> $to = "[email protected]";
$subject = 'my subject';
$message = 'I would like to work with you';
$headers = '';
$sent_message = wp_mail( $to, $subject, $message, $headers);
var_dump($sent_message); // i get boolean false here.
if ( $sent_message ) {
echo 'The test message was sent. Check your email inbox.';
} else {
echo 'The message was not sent!'; //this gets printed in d end.
}
</code></pre>
<p>Any help would be appreciated.</p>
|
[
{
"answer_id": 195830,
"author": "David",
"author_id": 31323,
"author_profile": "https://wordpress.stackexchange.com/users/31323",
"pm_score": 3,
"selected": false,
"text": "<p><code>wp_mail()</code> falls back to php's <code>mail()</code> function which requires a configured MTA (Message Transfer Agent) on your host. So either you install and configure such a MTA. If you're running a Linux like OS, <a href=\"https://wiki.archlinux.org/index.php/SSMTP\" rel=\"noreferrer\">SSMTP</a> is an easy solution on which you can use any mail-provider to send your system mails via SMTP. Another MTA would be <a href=\"https://en.wikipedia.org/wiki/Sendmail\" rel=\"noreferrer\">Sendmail</a>, a full featured, yet difficult to configure MTA.</p>\n\n<p>Or you simply use a plugin like <a href=\"https://wordpress.org/plugins/wp-mail-smtp/\" rel=\"noreferrer\">WP Mail SMTP</a> which implements a direct SMTP connection in PHP and bypass the <code>mail()</code> usage.</p>\n"
},
{
"answer_id": 387655,
"author": "Ronni",
"author_id": 205903,
"author_profile": "https://wordpress.stackexchange.com/users/205903",
"pm_score": 2,
"selected": false,
"text": "<p>If anybody stumbles across this old question:</p>\n<p>In my case, the reason was, I gave the site at localhost a name without a top-level domain. e.g. "mysite" (instead of "mysite.com"). So, WordPress assumed the "From" address to be "wordpress@mysite".</p>\n<p>Phpmailer (which is called by wp_mail) then raised the error: "Invalid address: (From): wordpress@mysite"</p>\n<p>Solution was to explicitly set the from address via the header:</p>\n<pre><code> $headers[] = 'From: Wordpress<[email protected]>';\n $sent_message = wp_mail( $to, $subject, $message, $headers );\n</code></pre>\n<p>Then wp_mail worked.</p>\n"
},
{
"answer_id": 410006,
"author": "rkok",
"author_id": 60301,
"author_profile": "https://wordpress.stackexchange.com/users/60301",
"pm_score": 0,
"selected": false,
"text": "<p>Expanding on Ronni's helpful answer, here's how you can override the <code>From:</code> address for all outgoing mail:</p>\n<pre class=\"lang-php prettyprint-override\"><code>if (defined('WP_CLI')) {\n WP_CLI::add_wp_hook('wp_mail_from', function () {\n return '[email protected]';\n });\n} else {\n add_filter('wp_mail_from', function () {\n return '[email protected]';\n });\n}\n</code></pre>\n<p>For my local development environment, I found it useful to place it in <code>wp-config.php</code>, at the very bottom, after <code>require_once ABSPATH . 'wp-settings.php';</code>.</p>\n<p>Added a workaround for wp-cli, since it doesn't provide <code>add_filter()</code> like WP would normally do.</p>\n"
}
] |
2015/07/28
|
[
"https://wordpress.stackexchange.com/questions/195827",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69020/"
] |
I'm trying to test wp\_mail() in my local.
When I var dump wp\_mail,I get Boolean false.This is my code
```
$to = "[email protected]";
$subject = 'my subject';
$message = 'I would like to work with you';
$headers = '';
$sent_message = wp_mail( $to, $subject, $message, $headers);
var_dump($sent_message); // i get boolean false here.
if ( $sent_message ) {
echo 'The test message was sent. Check your email inbox.';
} else {
echo 'The message was not sent!'; //this gets printed in d end.
}
```
Any help would be appreciated.
|
`wp_mail()` falls back to php's `mail()` function which requires a configured MTA (Message Transfer Agent) on your host. So either you install and configure such a MTA. If you're running a Linux like OS, [SSMTP](https://wiki.archlinux.org/index.php/SSMTP) is an easy solution on which you can use any mail-provider to send your system mails via SMTP. Another MTA would be [Sendmail](https://en.wikipedia.org/wiki/Sendmail), a full featured, yet difficult to configure MTA.
Or you simply use a plugin like [WP Mail SMTP](https://wordpress.org/plugins/wp-mail-smtp/) which implements a direct SMTP connection in PHP and bypass the `mail()` usage.
|
195,850 |
<p>I need to work with date function but I want to get day and month numerical and separate and pass it to a function.</p>
<p>For example, I want work for this function. </p>
<pre><code>function(day,month)
</code></pre>
<p>How can I get date of today on pass it to a function aside?</p>
|
[
{
"answer_id": 195852,
"author": "denis.stoyanov",
"author_id": 76287,
"author_profile": "https://wordpress.stackexchange.com/users/76287",
"pm_score": 1,
"selected": true,
"text": "<p>I think this will work for you (tried it and it works):</p>\n\n<pre><code>date('m', strtotime('0 month'));\ndate('d', strtotime('0 day'));\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/5733636/trying-to-get-the-number-of-the-month-before-of-the-current-month\">Here is a discussion</a> on the topic.</p>\n"
},
{
"answer_id": 195853,
"author": "M.Mazraeshahi",
"author_id": 76054,
"author_profile": "https://wordpress.stackexchange.com/users/76054",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the following functions:</p>\n\n<pre><code>time ();\n</code></pre>\n\n<p>return The time by seconds</p>\n\n<pre><code>date();\n</code></pre>\n\n<p>y- Year\nm- Month\nd- Day</p>\n\n<p>h- Hours\ni- Minute\ns- Second</p>\n\n<p>for ex:</p>\n\n<pre><code>date(\"Y-m-d H:i:s\");\n</code></pre>\n"
}
] |
2015/07/28
|
[
"https://wordpress.stackexchange.com/questions/195850",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71455/"
] |
I need to work with date function but I want to get day and month numerical and separate and pass it to a function.
For example, I want work for this function.
```
function(day,month)
```
How can I get date of today on pass it to a function aside?
|
I think this will work for you (tried it and it works):
```
date('m', strtotime('0 month'));
date('d', strtotime('0 day'));
```
[Here is a discussion](https://stackoverflow.com/questions/5733636/trying-to-get-the-number-of-the-month-before-of-the-current-month) on the topic.
|
195,864 |
<p>I wonder is there a way of running wp_register_script and enqueue with the help of foreach loop to manage label and dir?</p>
<p>For example, </p>
<pre><code>function wbs_app_components(){
$scripts_list=array(
'jquery' => ToDir('/jquery/jquery.js', $LIBRARY_DIR),
'bootstrap-jquery' => ToDir('/bootstrap/js/bootstrap.js', $LIBRARY_DIR),
}
foreach ($scripts_list as $key => $value){
// print_r($key);echo ("<br>");
// print_r($value);echo ("<br><br><br>");
wp_register_script($key,$value);
}
}
add_action( 'wp_enqueue_scripts', 'wbs_app_components');
</code></pre>
<p>However, funny thing is that seems NONE of the script are attached and no error reported!</p>
<p>I wonder what could be the reason</p>
|
[
{
"answer_id": 195871,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>You need to enqueue the scripts as well, not only register them. You can, however, just simply enqueue a script without registering it if you are not going to enqueue it conditionally.</p>\n\n<p>I would try something like this: (<em>Untested and requires PHP5.4+</em>)</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', enqueue_scripts, 11 );\nfunction enqueue_scripts()\n{\n /**\n * Build an array of scripts to enqueue\n * key = script handle\n * value = path to the script without the get_template_directory_uri()\n */\n $scripts = [\n 'script-1' => '/script.1.js',\n 'script-2' => '/js/script.2.js',\n 'script-3' => '/subfolder/script.3.js',\n ];\n foreach ( $scripts as $k=>$v )\n wp_enqueue_script( $k, get_template_directory_uri() . $v );\n}\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>As explanation to a comment to the answer, the <code>add_action()</code> call can go anywhere, it does not even needto be in the same template. It can go above or below the function declaration. I prefer to add the <code>add_action()</code> call above the function as this just makes more sense when you think about closures. When using closures, the code above will look something like this:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', function ()\n{\n /**\n * Build an array of scripts to enqueue\n * key = script handle\n * value = path to the script without the get_template_directory_uri()\n */\n $scripts = [\n 'script-1' => '/script.1.js',\n 'script-2' => '/js/script.2.js',\n 'script-3' => '/subfolder/script.3.js',\n ];\n foreach ( $scripts as $k=>$v )\n wp_enqueue_script( $k, get_template_directory_uri() . $v );\n}, 11 );\n</code></pre>\n\n<p>So you see, it just makes more sense :-)</p>\n"
},
{
"answer_id": 195873,
"author": "MMK",
"author_id": 65350,
"author_profile": "https://wordpress.stackexchange.com/users/65350",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to enqueue your files separately use this code and still be able to register them(probably you want to use it after wards as well) then use this:</p>\n\n<pre><code>$template_directory = get_template_directory_uri();\n$array_of_js_files = array( \n array(\n 'script_handle1',\n $template_directory . '/your_directory/file1.js',\n array(), //any dependency your script has\n '1.0.0', // version number 1.0.0 is an example\n true // in footer or not\n ),\n array(\n 'script_handle2',\n $template_directory . '/your_directory/file2.js',\n array(),\n '1.0.0',\n true\n )\n);\n\n$array_of_css_files = array( \n array(\n 'css_handle1',\n $template_directory . '/your_directory/file1.css',\n array(), //any dependency your css file has\n '1.0.0', // version number 1.0.0 is an example\n 'screen' // media\n ),\n array(\n 'css_handle2',\n $template_directory . '/your_directory/file2.css',\n array(),\n '1.0.0',\n 'screen'\n )\n);\n\n\nforeach( $array_of_js_files as $data ){\n wp_register_script( $data[0], $data[1], $data[2], $data[3], $data[4] );\n wp_enqueue_script( $data[0] );\n}\n\n// to enqueue your script or css file later simply refer to your the handle you created\n\nforeach( $array_of_css_files as $data ){\n wp_register_style( $data[0], $data[1], $data[2], $data[3], $data[4] );\n wp_enqueue_style( $data[0] );\n}\n</code></pre>\n\n<p>Note that this above code is untested but it should work.</p>\n"
}
] |
2015/07/28
|
[
"https://wordpress.stackexchange.com/questions/195864",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38535/"
] |
I wonder is there a way of running wp\_register\_script and enqueue with the help of foreach loop to manage label and dir?
For example,
```
function wbs_app_components(){
$scripts_list=array(
'jquery' => ToDir('/jquery/jquery.js', $LIBRARY_DIR),
'bootstrap-jquery' => ToDir('/bootstrap/js/bootstrap.js', $LIBRARY_DIR),
}
foreach ($scripts_list as $key => $value){
// print_r($key);echo ("<br>");
// print_r($value);echo ("<br><br><br>");
wp_register_script($key,$value);
}
}
add_action( 'wp_enqueue_scripts', 'wbs_app_components');
```
However, funny thing is that seems NONE of the script are attached and no error reported!
I wonder what could be the reason
|
You need to enqueue the scripts as well, not only register them. You can, however, just simply enqueue a script without registering it if you are not going to enqueue it conditionally.
I would try something like this: (*Untested and requires PHP5.4+*)
```
add_action( 'wp_enqueue_scripts', enqueue_scripts, 11 );
function enqueue_scripts()
{
/**
* Build an array of scripts to enqueue
* key = script handle
* value = path to the script without the get_template_directory_uri()
*/
$scripts = [
'script-1' => '/script.1.js',
'script-2' => '/js/script.2.js',
'script-3' => '/subfolder/script.3.js',
];
foreach ( $scripts as $k=>$v )
wp_enqueue_script( $k, get_template_directory_uri() . $v );
}
```
EDIT
----
As explanation to a comment to the answer, the `add_action()` call can go anywhere, it does not even needto be in the same template. It can go above or below the function declaration. I prefer to add the `add_action()` call above the function as this just makes more sense when you think about closures. When using closures, the code above will look something like this:
```
add_action( 'wp_enqueue_scripts', function ()
{
/**
* Build an array of scripts to enqueue
* key = script handle
* value = path to the script without the get_template_directory_uri()
*/
$scripts = [
'script-1' => '/script.1.js',
'script-2' => '/js/script.2.js',
'script-3' => '/subfolder/script.3.js',
];
foreach ( $scripts as $k=>$v )
wp_enqueue_script( $k, get_template_directory_uri() . $v );
}, 11 );
```
So you see, it just makes more sense :-)
|
195,945 |
<p>I am using an image as my site logo, and the image displays fine on the site. However, while the image is inside of an 'a' tag, its not clickable. Here's my code:</p>
<pre><code><div class="site-branding">
<a href="<?php echo bloginfo('url'); ?>">
<img class="site-logo img-responsive" src="<?php echo bloginfo('url'); ?>/wp-content/uploads/2015/07/logo-height-150.png" />
</a>
<img class="description-n-landscape img-responsive" src="<?php echo bloginfo('url'); ?>/wp-content/uploads/2015/07/description-n-landscape.png">
</div>
</code></pre>
|
[
{
"answer_id": 195957,
"author": "Sereyboth Yorn",
"author_id": 76938,
"author_profile": "https://wordpress.stackexchange.com/users/76938",
"pm_score": 2,
"selected": false,
"text": "<p>Can you try with this code? Because <code>bloginfo()</code> <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/general-template.php#L578\" rel=\"nofollow\">does already <code>echo</code></a>, you need to remove the <code>echo</code>.</p>\n\n<pre><code><div class=\"site-branding\">\n <a href=\"<?php bloginfo('url'); ?>\">\n <img class=\"site-logo img-responsive\" src=\"<?php bloginfo('url'); ?>/wp-content/uploads/2015/07/logo-height-150.png\" />\n </a>\n <img class=\"description-n-landscape img-responsive\" src=\"<?php bloginfo('url'); ?>/wp-content/uploads/2015/07/description-n-landscape.png\" />\n\n</div>\n</code></pre>\n"
},
{
"answer_id": 195969,
"author": "krillebimbim",
"author_id": 76421,
"author_profile": "https://wordpress.stackexchange.com/users/76421",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the <a href=\"https://codex.wordpress.org/Function_Reference/home_url\" rel=\"nofollow\"><code>home_url()</code></a> function for your <code>href</code> and don't forget to sanitize the URL, when putting it into tag attributes like <code>href</code>, with <a href=\"https://codex.wordpress.org/Function_Reference/esc_url\" rel=\"nofollow\"><code>esc_url()</code></a>.</p>\n\n<pre><code><?php echo esc_url( home_url( '/' ) ); ?>\n</code></pre>\n"
},
{
"answer_id": 195971,
"author": "Sourav Mukhopadhyay",
"author_id": 76917,
"author_profile": "https://wordpress.stackexchange.com/users/76917",
"pm_score": 0,
"selected": false,
"text": "<p>Just Change</p>\n\n<pre><code><a href=\"<?php echo bloginfo('url'); ?>\">\n</code></pre>\n\n<p>to</p>\n\n<pre><code><a href=\"<?php echo home_url(); ?>\">\n</code></pre>\n\n<p>That's all. I am sure this will work.</p>\n"
},
{
"answer_id": 195976,
"author": "Tejas",
"author_id": 66047,
"author_profile": "https://wordpress.stackexchange.com/users/66047",
"pm_score": 1,
"selected": false,
"text": "<p>Because <code>bloginfo()</code> <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/general-template.php#L578\" rel=\"nofollow\">does already <code>echo</code></a>, you need to remove <code>echo</code> from your posted snippet, making the href <code><?php bloginfo('url'); ?></code>.</p>\n"
}
] |
2015/07/29
|
[
"https://wordpress.stackexchange.com/questions/195945",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14578/"
] |
I am using an image as my site logo, and the image displays fine on the site. However, while the image is inside of an 'a' tag, its not clickable. Here's my code:
```
<div class="site-branding">
<a href="<?php echo bloginfo('url'); ?>">
<img class="site-logo img-responsive" src="<?php echo bloginfo('url'); ?>/wp-content/uploads/2015/07/logo-height-150.png" />
</a>
<img class="description-n-landscape img-responsive" src="<?php echo bloginfo('url'); ?>/wp-content/uploads/2015/07/description-n-landscape.png">
</div>
```
|
Can you try with this code? Because `bloginfo()` [does already `echo`](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/general-template.php#L578), you need to remove the `echo`.
```
<div class="site-branding">
<a href="<?php bloginfo('url'); ?>">
<img class="site-logo img-responsive" src="<?php bloginfo('url'); ?>/wp-content/uploads/2015/07/logo-height-150.png" />
</a>
<img class="description-n-landscape img-responsive" src="<?php bloginfo('url'); ?>/wp-content/uploads/2015/07/description-n-landscape.png" />
</div>
```
|
195,960 |
<p>How can I show child categories under there parent category in the wordpress admin? On a post the format of the category box would look like this:</p>
<p>Category 1</p>
<ul>
<li>Sub-Category 1.1</li>
<li>Sub-Category 1.2</li>
</ul>
<p>Category 2</p>
|
[
{
"answer_id": 195963,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": 1,
"selected": true,
"text": "<p>EDIT:</p>\n\n<p>On a post page, the categories are already seen in hierarchical manner but with checkboxes. So, I have assumed that you have to show list of all the categories/subcategories somewhere in the admin panel in following format.</p>\n\n<ul>\n<li>Category 1 \n\n<ul>\n<li>Sub-Category 1.1 </li>\n<li>Sub-Category 1.2 </li>\n</ul></li>\n<li>Category 2</li>\n</ul>\n\n<p>So, presentation is upto you, I have just given logic to pull the necessary data i.e. list of all the categories along with subcategories.</p>\n\n<pre><code> $arg1 = array(\n 'parent' => 0,\n 'orderby' => 'name',\n 'hide_empty' => 0,\n 'pad_counts' => false \n );\n\n $categories = get_terms('category', $arg1); //or use your custom taxonomy name\n\n if( !empty($categories) && is_array($categories) ){\n\n echo '<ul>'; \n\n foreach($categories as $cat){\n\n echo '<li>'.$cat->name;\n\n $arg2 = array(\n 'child_of' => $cat->term_id,\n 'orderby' => 'name',\n 'hide_empty' => 0,\n 'pad_counts' => false \n );\n\n $sub_categories = get_terms('category', $arg2); //or use your custom taxonomy name\n\n if(!empty($sub_categories) && is_array($sub_categories)){\n\n echo '<ul>'; \n\n foreach($sub_categories as $scat){\n\n echo '<li>'.$scat->name.'</li>';\n }\n echo '</ul>';\n }\n echo '</li>';\n }\n echo '</ul>';\n }\n</code></pre>\n"
},
{
"answer_id": 196000,
"author": "prempal sharma",
"author_id": 76953,
"author_profile": "https://wordpress.stackexchange.com/users/76953",
"pm_score": -1,
"selected": false,
"text": "<p>use this code for solving your problem.</p>\n\n<pre><code><?php \n $args = array( 'orderby' =>'name',\n 'texonomy' =>'category',\n 'child_of' =>0,\n 'parent' =>0 );\n\n $cats = get_categories($args);\n foreach ($cats as $cat) {\n echo $cat->name;\n $arg = array('orderby' => 'name',\n 'child_of' =>0,\n 'parent' =>$cat->term_id);\n $sub_cats =get_categories($arg);\n\n foreach ($sub_cats as $sub) {\n echo '<hr><br>';\n echo '<h3>'.$sub->name.'</h3>';\n echo '<hr><br>';\n $args = array(\n 'post_type' => 'post',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'category',\n 'terms' => $sub->term_id,\n ),\n ),\n );\n\n $query = new WP_query( $args);\n //echo \"<pre>\"; print_r($query); echo \"</pre>\";\n while($query->have_posts()) : $query->the_post();\n echo \"<br>\";\n the_title();\n echo \"<br>\";\n the_content();\n endwhile;\n echo \"<hr>\";\n }\n }\n ?>\n</code></pre>\n"
}
] |
2015/07/29
|
[
"https://wordpress.stackexchange.com/questions/195960",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45945/"
] |
How can I show child categories under there parent category in the wordpress admin? On a post the format of the category box would look like this:
Category 1
* Sub-Category 1.1
* Sub-Category 1.2
Category 2
|
EDIT:
On a post page, the categories are already seen in hierarchical manner but with checkboxes. So, I have assumed that you have to show list of all the categories/subcategories somewhere in the admin panel in following format.
* Category 1
+ Sub-Category 1.1
+ Sub-Category 1.2
* Category 2
So, presentation is upto you, I have just given logic to pull the necessary data i.e. list of all the categories along with subcategories.
```
$arg1 = array(
'parent' => 0,
'orderby' => 'name',
'hide_empty' => 0,
'pad_counts' => false
);
$categories = get_terms('category', $arg1); //or use your custom taxonomy name
if( !empty($categories) && is_array($categories) ){
echo '<ul>';
foreach($categories as $cat){
echo '<li>'.$cat->name;
$arg2 = array(
'child_of' => $cat->term_id,
'orderby' => 'name',
'hide_empty' => 0,
'pad_counts' => false
);
$sub_categories = get_terms('category', $arg2); //or use your custom taxonomy name
if(!empty($sub_categories) && is_array($sub_categories)){
echo '<ul>';
foreach($sub_categories as $scat){
echo '<li>'.$scat->name.'</li>';
}
echo '</ul>';
}
echo '</li>';
}
echo '</ul>';
}
```
|
195,962 |
<p>I have installed html5 blank template and I have created sub theme too by creating <code>style.css</code> and <code>functions.php</code>. But how should I get rid off default CSS styles that come from parent theme?</p>
|
[
{
"answer_id": 195977,
"author": "Tejas",
"author_id": 66047,
"author_profile": "https://wordpress.stackexchange.com/users/66047",
"pm_score": -1,
"selected": false,
"text": "<p>Go to the parent theme's functions.php and remove any enqueued styles you don't want.</p>\n"
},
{
"answer_id": 195979,
"author": "Hari Om Gupta",
"author_id": 68792,
"author_profile": "https://wordpress.stackexchange.com/users/68792",
"pm_score": 3,
"selected": true,
"text": "<p>there are two ways, \nfirst: if you want to remove default style, just dequeue them using <code>wp_dequeue_style( 'style_file_name_here' )</code>.\nsecond: you can rename the existing file and create a new one with the same name, just place style hook info into new style file, like:</p>\n\n<pre><code>/*\nTheme Name: Theme name\nAuthor: Author name\n*/\n</code></pre>\n\n<p>remember, the second way is unprofessional, but you can use this one as well. </p>\n"
}
] |
2015/07/29
|
[
"https://wordpress.stackexchange.com/questions/195962",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76941/"
] |
I have installed html5 blank template and I have created sub theme too by creating `style.css` and `functions.php`. But how should I get rid off default CSS styles that come from parent theme?
|
there are two ways,
first: if you want to remove default style, just dequeue them using `wp_dequeue_style( 'style_file_name_here' )`.
second: you can rename the existing file and create a new one with the same name, just place style hook info into new style file, like:
```
/*
Theme Name: Theme name
Author: Author name
*/
```
remember, the second way is unprofessional, but you can use this one as well.
|
195,981 |
<p>with the support of ACF team I created a page where I list the values from a Taxonomy Custom Field (custom field named cognome_nome) alphabetically.
I explain:</p>
<p>Term 1</p>
<ul>
<li>Name: Elena P</li>
<li>slug: elena_p</li>
<li>cognome_nome: P Elena</li>
</ul>
<p>Term 2</p>
<ul>
<li>Name: Andrea B</li>
<li>slug: andrea_b</li>
<li>cognome_nome: B Andrea</li>
</ul>
<p>The list will be:</p>
<ul>
<li>B Andrea</li>
<li>P Elena</li>
</ul>
<p>But how can I add the link to the term page? I tried with get_term_link( $term ) but It gives me the link of the last author I added to the taxonomy.</p>
<p>Here's my code:</p>
<pre><code>$terms = get_terms( 'authors', $args );
$values = array();
foreach($terms as $term):
array_push($values, get_field('cognome_nome', $term));
endforeach;
sort($values);
// display values
foreach ($values as $value) {
echo "<div> <a href='" . get_term_link( $term ) . "'</a>" . get_field('cognome_nome', $term) . "</div>";
echo $value;
}
</code></pre>
<p>Thank you</p>
|
[
{
"answer_id": 195993,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": true,
"text": "<p>I do not know how ACF works or how its data is stored, but in general, I would just use <code>usort()</code> to sort the returned array of terms via the ACF value of <code>cognome_nome</code>. Note that <code>array_push</code> is a bit expensive to use, so try to avoid that ;-)</p>\n\n<p>As I stated in comments, your code does not make much sense to me. You have two separate <code>foreach</code> loops, which is fine, but you are trying to use the value of the first <code>foreach</code> loop's value (<em><code>$term</code></em>) in the second one, which will not work. In a <code>foreach</code> loop, the value of the last key remains outside/after the <code>foreach</code> loop, which means that <code>$term</code> will always be set to the last term. Because of this, and because you use <code>$term</code> in your second <code>foreach</code> loop as is, all values will be set to the last term of your <code>$terms</code> object. That is exactly what you are seeing.</p>\n\n<p>In general, this is how I would tackle this issue</p>\n\n<pre><code>$terms = get_terms( 'authors', $args );\n/**\n * Remember the usort bug. Use @usort to cut the bug's wings and feet ;-)\n */\n@usort( $terms, function ( $a, $b )\n{\n /**\n * Get our ACF Data\n * Just make sure that my logic is correct here and that you actually get data from get_field\n */\n $array_a = get_field( 'cognome_nome', $a );\n $array_b = get_field( 'cognome_nome', $b );\n\n if ( $array_a ) {\n $sort_a = $array_a;\n } else {\n $sort_a = 'zzz'; //Kind of fall back to add posts without field last\n }\n\n if ( $array_b ) {\n $sort_b = $array_b;\n } else {\n $sort_b = 'zzz'; //Kind of fall back to add posts without field last\n }\n\n // Sort by these ACF data\n return strcasecmp ( $sort_a, $sort_b );\n});\n</code></pre>\n\n<p>This will take care of sorting. You can just then loop through your terms normally and output them as you would normally do</p>\n"
},
{
"answer_id": 195996,
"author": "prempal sharma",
"author_id": 76953,
"author_profile": "https://wordpress.stackexchange.com/users/76953",
"pm_score": -1,
"selected": false,
"text": "<p>i thinks this function are used for get term link.</p>\n\n<pre><code>get_term_link($terms,texonomy_name);\n</code></pre>\n\n<p>this function is perfectly work.</p>\n"
},
{
"answer_id": 294110,
"author": "Parveen Chauhan",
"author_id": 136860,
"author_profile": "https://wordpress.stackexchange.com/users/136860",
"pm_score": -1,
"selected": false,
"text": "<pre><code>foreach ($values as $value) {\n echo \"<div> <a href='\" . get_term_link($value ) . \"'</a>\" . \n get_field('cognome_nome', $term) . \"</div>\";\n echo $value;\n}\n</code></pre>\n"
}
] |
2015/07/29
|
[
"https://wordpress.stackexchange.com/questions/195981",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76249/"
] |
with the support of ACF team I created a page where I list the values from a Taxonomy Custom Field (custom field named cognome\_nome) alphabetically.
I explain:
Term 1
* Name: Elena P
* slug: elena\_p
* cognome\_nome: P Elena
Term 2
* Name: Andrea B
* slug: andrea\_b
* cognome\_nome: B Andrea
The list will be:
* B Andrea
* P Elena
But how can I add the link to the term page? I tried with get\_term\_link( $term ) but It gives me the link of the last author I added to the taxonomy.
Here's my code:
```
$terms = get_terms( 'authors', $args );
$values = array();
foreach($terms as $term):
array_push($values, get_field('cognome_nome', $term));
endforeach;
sort($values);
// display values
foreach ($values as $value) {
echo "<div> <a href='" . get_term_link( $term ) . "'</a>" . get_field('cognome_nome', $term) . "</div>";
echo $value;
}
```
Thank you
|
I do not know how ACF works or how its data is stored, but in general, I would just use `usort()` to sort the returned array of terms via the ACF value of `cognome_nome`. Note that `array_push` is a bit expensive to use, so try to avoid that ;-)
As I stated in comments, your code does not make much sense to me. You have two separate `foreach` loops, which is fine, but you are trying to use the value of the first `foreach` loop's value (*`$term`*) in the second one, which will not work. In a `foreach` loop, the value of the last key remains outside/after the `foreach` loop, which means that `$term` will always be set to the last term. Because of this, and because you use `$term` in your second `foreach` loop as is, all values will be set to the last term of your `$terms` object. That is exactly what you are seeing.
In general, this is how I would tackle this issue
```
$terms = get_terms( 'authors', $args );
/**
* Remember the usort bug. Use @usort to cut the bug's wings and feet ;-)
*/
@usort( $terms, function ( $a, $b )
{
/**
* Get our ACF Data
* Just make sure that my logic is correct here and that you actually get data from get_field
*/
$array_a = get_field( 'cognome_nome', $a );
$array_b = get_field( 'cognome_nome', $b );
if ( $array_a ) {
$sort_a = $array_a;
} else {
$sort_a = 'zzz'; //Kind of fall back to add posts without field last
}
if ( $array_b ) {
$sort_b = $array_b;
} else {
$sort_b = 'zzz'; //Kind of fall back to add posts without field last
}
// Sort by these ACF data
return strcasecmp ( $sort_a, $sort_b );
});
```
This will take care of sorting. You can just then loop through your terms normally and output them as you would normally do
|
196,026 |
<p>I want to modify a function in a plugin. It is declared in the plugin's main file like this:</p>
<pre><code>class WCPGSK_Main {
...
public function wcpgsk_email_after_order_table($order) {
...
}
}
</code></pre>
<p>Add called from there like this:</p>
<pre><code>add_action( 'woocommerce_email_after_order_table', array($this, 'wcpgsk_email_after_order_table') );
</code></pre>
<p>I guess it would be possible to replace it if had an access to the class in functions.php. Then I would be able to write something like this:</p>
<pre><code>$wcpgsk = new WCPGSK_Main;
remove_action( 'woocommerce_email_after_order_table', array($wcpgsk, 'wcpgsk_email_after_order_table') );
function customized_wcpgsk_email_after_order_table($order) {
...
}
add_action( 'woocommerce_email_after_order_table', array($wcpgsk, 'customized_wcpgsk_email_after_order_table') );
</code></pre>
<p>My thought to get an access to the class in the functions.php file was to include the file where the class is declared in functions.php:</p>
<pre><code>require_once('/wp-content/plugins/woocommerce-poor-guys-swiss-knife/woocommerce-poor-guys-swiss-knife.php');
$wcpgsk = new WCPGSK_Main;
...
</code></pre>
<p>But this does not work because the plugin's file is included when the plugin is getting initialized in WordPress, I guess. </p>
<p>Is there a way to rewrite the function without touching plugin's files?</p>
|
[
{
"answer_id": 196029,
"author": "passatgt",
"author_id": 8038,
"author_profile": "https://wordpress.stackexchange.com/users/8038",
"pm_score": 4,
"selected": true,
"text": "<p>This should work:</p>\n\n<pre><code>add_action( 'woocommerce_init', 'remove_wcpgsk_email_order_table' );\nfunction remove_wcpgsk_email_order_table() {\n\n global $wcpgsk;\n remove_action( 'woocommerce_email_after_order_table', array( $wcpgsk, 'wcpgsk_email_after_order_table' ) );\n\n}\n</code></pre>\n"
},
{
"answer_id": 196036,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 4,
"selected": false,
"text": "<p>If your plugin is registered like this:</p>\n\n<pre><code>class Test_Class_Parent {\n function __construct() {\n add_action('wp_head',array($this,'test_method'));\n }\n\n function test_method() {\n echo 'Echoed from the parent';\n }\n}\n$p = new Test_Class_Parent();\n</code></pre>\n\n<p>Then you should be able to remove the filter by accessing the global:</p>\n\n<pre><code>class Test_Class_Child extends Test_Class_Parent {\n function __construct() {\n $this->unregister_parent_hook();\n add_action('wp_head',array($this,'test_method'));\n }\n\n function unregister_parent_hook() {\n global $p;\n remove_action('wp_head',array($p,'test_method'));\n }\n\n function test_method() {\n echo 'Echoed from the child';\n }\n}\n$c = new Test_Class_Child();\n</code></pre>\n\n<p>Otherwise, you will need to crawl the <code>$wp_filter</code> <code>global</code> for the registration key:</p>\n\n<pre><code>class Test_Class_Child extends Test_Class_Parent {\n function __construct() {\n $this->unregister_parent_hook();\n add_action('wp_head',array($this,'test_method'));\n }\n\n function unregister_parent_hook() {\n global $wp_filter;\n if (!empty($wp_filter['wp_head'])) {\n foreach($wp_filter['wp_head'] as $cb) {\n foreach ($cb as $k => $v) {\n if (\n isset($v['function'])\n && is_a($v['function'][0],'Test_Class_Parent')\n && isset($v['function'][1])\n && 'test_method' == $v['function'][1]\n ) {\n remove_action('wp_head',$k);\n }\n }\n }\n }\n }\n\n function test_method() {\n echo 'Echoed from the child';\n }\n}\n$c = new Test_Class_Child();\n</code></pre>\n\n<p>This is resource intensive and should really not be done unless you have no other choice. </p>\n"
},
{
"answer_id": 196082,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 1,
"selected": false,
"text": "<p>That plugin makes its init function <code>wcpgsk_init()</code> pluggable, so another way to override it is to define it first in a must-use plugin (as it's too late in your theme's \"functions.php\"). So you could put your override in \"wp-content/mu-plugins/functions.php\":</p>\n\n<pre><code>function wcpgsk_init() {\n global $wcpgsk, $wcpgsk_about, $wcpgsk_options, $wcpgsk_session, $wcpgsk_woocommerce_active; \n //only continue loading\n if ( $wcpgsk_woocommerce_active && version_compare( WOOCOMMERCE_VERSION, \"2.0\" ) >= 0 ) {\n $FILE = WP_PLUGIN_DIR . '/woocommerce-poor-guys-swiss-knife/woocommerce-poor-guys-swiss-knife.php'; // Fake __FILE__\n $dirname = dirname( $FILE ) . '/';\n $wcpgsk_options = get_option('wcpgsk_settings', true);\n require_once( $dirname . 'classes/woocommerce-poor-guys-swiss-knife.php' );\n require_once( $dirname . 'classes/woocommerce-poor-guys-swiss-knife-about.php' ); \n require_once( $dirname . 'wcpgsk-af.php' );\n\n if ( !is_admin() ) :\n add_action( 'plugins_loaded', 'wcpgsk_load_wcsession_helper' );\n endif;\n\n // Your override.\n class My_WCPGSK_Main extends WCPGSK_Main {\n public function wcpgsk_email_after_order_table($order) {\n echo \"O la la\";\n }\n }\n define( 'WCRGSK_DOMAIN', WCPGSK_DOMAIN ); // Fix typo! (WooCommerce Rich Guys Swiss Knife?)\n\n //load into our global\n $wcpgsk = new My_WCPGSK_Main( $FILE );\n $wcpgsk->version = '2.2.4'; \n $wcpgsk->wcpgsk_hook_woocommerce_filters();\n\n\n } elseif ( version_compare( WOOCOMMERCE_VERSION, \"2.0\" ) < 0 ) {\n add_action( 'admin_notices', 'wcpgsk_woocommerce_version_message', 0 ) ; \n return;\n } else {\n return;\n }\n}\n</code></pre>\n\n<p>But an even better way to override it is to install <code>runkit</code> (<a href=\"https://github.com/padraic/runkit\" rel=\"nofollow\">https://github.com/padraic/runkit</a>) and then just replace it directly in your theme's \"functions.php\":</p>\n\n<pre><code>add_action( 'init', function () {\n $code = <<<'EOD'\necho \"O la la\";\nEOD;\n runkit_method_redefine(\n 'WCPGSK_Main',\n 'wcpgsk_email_after_order_table',\n '$order',\n $code,\n RUNKIT_ACC_PUBLIC\n );\n} );\n</code></pre>\n\n<p>(That's a joke, btw.)</p>\n"
}
] |
2015/07/29
|
[
"https://wordpress.stackexchange.com/questions/196026",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73366/"
] |
I want to modify a function in a plugin. It is declared in the plugin's main file like this:
```
class WCPGSK_Main {
...
public function wcpgsk_email_after_order_table($order) {
...
}
}
```
Add called from there like this:
```
add_action( 'woocommerce_email_after_order_table', array($this, 'wcpgsk_email_after_order_table') );
```
I guess it would be possible to replace it if had an access to the class in functions.php. Then I would be able to write something like this:
```
$wcpgsk = new WCPGSK_Main;
remove_action( 'woocommerce_email_after_order_table', array($wcpgsk, 'wcpgsk_email_after_order_table') );
function customized_wcpgsk_email_after_order_table($order) {
...
}
add_action( 'woocommerce_email_after_order_table', array($wcpgsk, 'customized_wcpgsk_email_after_order_table') );
```
My thought to get an access to the class in the functions.php file was to include the file where the class is declared in functions.php:
```
require_once('/wp-content/plugins/woocommerce-poor-guys-swiss-knife/woocommerce-poor-guys-swiss-knife.php');
$wcpgsk = new WCPGSK_Main;
...
```
But this does not work because the plugin's file is included when the plugin is getting initialized in WordPress, I guess.
Is there a way to rewrite the function without touching plugin's files?
|
This should work:
```
add_action( 'woocommerce_init', 'remove_wcpgsk_email_order_table' );
function remove_wcpgsk_email_order_table() {
global $wcpgsk;
remove_action( 'woocommerce_email_after_order_table', array( $wcpgsk, 'wcpgsk_email_after_order_table' ) );
}
```
|
196,050 |
<p>Contributors on our wordpress site can't preview posts. I'd like them to be able to preview any post (not just theirs) and this should include custom post types.</p>
<p>I can't find a specific capability to add to the contributor role like I've done with other capabilities.</p>
|
[
{
"answer_id": 196209,
"author": "John Blackbourn",
"author_id": 27051,
"author_profile": "https://wordpress.stackexchange.com/users/27051",
"pm_score": 2,
"selected": false,
"text": "<p>Unfortunately, WordPress doesn't use a separate capability for previewing posts. A user needs the ability to <em>edit</em> a post in order to preview it. As seen in <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/query.php#L3549\" rel=\"nofollow noreferrer\">the WP_Query::get_posts() method</a>:</p>\n\n<pre><code>// User must have edit permissions on the draft to preview.\nif ( ! current_user_can($edit_cap, $this->posts[0]->ID) ) {\n $this->posts = array();\n}\n</code></pre>\n\n<p>What you could do is use a combination of the <code>posts_results</code> filter (which is applied before unpublished posts are handled) and the <code>the_posts</code> filter (which is applied after), to re-populate the posts array if the user is a Contributor.</p>\n\n<p>Please double-check this for any security implications of allowing lower level users access to preview unpublished content.</p>\n\n<p>Untested example:</p>\n\n<pre><code>class wpse_196050 {\n\n protected $posts = array();\n\n public function __construct() {\n add_filter( 'posts_results', array( $this, 'filter_posts_results' ), 10, 2 );\n add_filter( 'the_posts', array( $this, 'filter_the_posts' ), 10, 2 );\n }\n\n public function filter_posts_results( array $posts, WP_Query $query ) {\n $this->posts = []; // Reset posts array for each WP_Query instance\n if ( $query->is_preview ) {\n $this->posts = $posts;\n }\n return $posts;\n }\n\n public function filter_the_posts( array $posts, WP_Query $query ) {\n if ( ! empty( $this->posts ) && current_user_can( 'edit_posts' ) ) {\n $posts = $this->posts;\n }\n return $posts;\n }\n\n}\n\nnew wpse_196050;\n</code></pre>\n"
},
{
"answer_id": 299479,
"author": "Horakiri Suo",
"author_id": 140561,
"author_profile": "https://wordpress.stackexchange.com/users/140561",
"pm_score": 2,
"selected": false,
"text": "<p>Using a custom plugin, and based off <a href=\"https://wordpress.stackexchange.com/questions/299049/allow-contributor-to-view-own-scheduled-post/299478#299478\">this</a> answer:</p>\n\n<pre><code>//allow post preview if you are the post owner, whatever role you might have (e.g. contributor)\nfunction jv_change_post( $posts ) {\n if(is_preview() && !empty($posts)){\n if(user_can('contributor')) \n $posts[0]->post_status = 'publish';\n }\n\n return $posts;\n}\nadd_filter( 'posts_results', 'jv_change_post', 10, 2 );\n</code></pre>\n\n<p>This basically makes 'future' posts pretend like they're already published (but only in the context of the current query), which makes it possible for the contributor to view them.</p>\n"
}
] |
2015/07/29
|
[
"https://wordpress.stackexchange.com/questions/196050",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48623/"
] |
Contributors on our wordpress site can't preview posts. I'd like them to be able to preview any post (not just theirs) and this should include custom post types.
I can't find a specific capability to add to the contributor role like I've done with other capabilities.
|
Unfortunately, WordPress doesn't use a separate capability for previewing posts. A user needs the ability to *edit* a post in order to preview it. As seen in [the WP\_Query::get\_posts() method](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/query.php#L3549):
```
// User must have edit permissions on the draft to preview.
if ( ! current_user_can($edit_cap, $this->posts[0]->ID) ) {
$this->posts = array();
}
```
What you could do is use a combination of the `posts_results` filter (which is applied before unpublished posts are handled) and the `the_posts` filter (which is applied after), to re-populate the posts array if the user is a Contributor.
Please double-check this for any security implications of allowing lower level users access to preview unpublished content.
Untested example:
```
class wpse_196050 {
protected $posts = array();
public function __construct() {
add_filter( 'posts_results', array( $this, 'filter_posts_results' ), 10, 2 );
add_filter( 'the_posts', array( $this, 'filter_the_posts' ), 10, 2 );
}
public function filter_posts_results( array $posts, WP_Query $query ) {
$this->posts = []; // Reset posts array for each WP_Query instance
if ( $query->is_preview ) {
$this->posts = $posts;
}
return $posts;
}
public function filter_the_posts( array $posts, WP_Query $query ) {
if ( ! empty( $this->posts ) && current_user_can( 'edit_posts' ) ) {
$posts = $this->posts;
}
return $posts;
}
}
new wpse_196050;
```
|
196,055 |
<p>I have a list of products in WooCommerce that have titles like so:</p>
<p><strong><em>Please note: The "groups" are just for myself, they are not categories etc. All products are the same type of product, just two types of products have different codes (Z and UK)</em></strong></p>
<p><strong>"Group 1" -</strong> Unique numbers</p>
<ul>
<li>5000</li>
<li>4999</li>
<li>4998</li>
<li>4997</li>
<li>4996</li>
<li>etc etc</li>
</ul>
<p><strong>"Group 2" -</strong> Unique numbers that begin with a <strong>Z</strong></p>
<ul>
<li>Z5000</li>
<li>Z4999</li>
<li>Z4998</li>
<li>Z4997</li>
<li>Z4996</li>
<li>etc etc</li>
</ul>
<p><strong>"Group 3" -</strong> Unique numbers that begin with <strong>UK</strong></p>
<ul>
<li>UK5000</li>
<li>UK4999</li>
<li>UK4998</li>
<li>UK4997</li>
<li>UK4996</li>
<li>etc etc</li>
</ul>
<p>Obviously by default, WordPress orders by date so on the product's archive page, they look like this:</p>
<ul>
<li>UK4020</li>
<li>2122</li>
<li>Z3122</li>
<li>4999</li>
<li>UK1001</li>
<li>etc etc</li>
</ul>
<p>What I would like (but can't seem to find any answer with my Google-fu), is to custom order my products like so: </p>
<ul>
<li><strong>Unique numbers, in descending order</strong></li>
<li><strong>Unique numbers that begin with Z, in descending order</strong></li>
<li><strong>Unique numbers that begin with UK, in descending order</strong></li>
</ul>
<p>... So my products look like this: </p>
<ul>
<li>5000,</li>
<li>4999,</li>
<li>etc</li>
<li>Z5000,</li>
<li>Z4999,</li>
<li>etc</li>
<li>UK5000,</li>
<li>UK4999</li>
<li>etc</li>
</ul>
<p>Hope the above makes sense!</p>
|
[
{
"answer_id": 196209,
"author": "John Blackbourn",
"author_id": 27051,
"author_profile": "https://wordpress.stackexchange.com/users/27051",
"pm_score": 2,
"selected": false,
"text": "<p>Unfortunately, WordPress doesn't use a separate capability for previewing posts. A user needs the ability to <em>edit</em> a post in order to preview it. As seen in <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/query.php#L3549\" rel=\"nofollow noreferrer\">the WP_Query::get_posts() method</a>:</p>\n\n<pre><code>// User must have edit permissions on the draft to preview.\nif ( ! current_user_can($edit_cap, $this->posts[0]->ID) ) {\n $this->posts = array();\n}\n</code></pre>\n\n<p>What you could do is use a combination of the <code>posts_results</code> filter (which is applied before unpublished posts are handled) and the <code>the_posts</code> filter (which is applied after), to re-populate the posts array if the user is a Contributor.</p>\n\n<p>Please double-check this for any security implications of allowing lower level users access to preview unpublished content.</p>\n\n<p>Untested example:</p>\n\n<pre><code>class wpse_196050 {\n\n protected $posts = array();\n\n public function __construct() {\n add_filter( 'posts_results', array( $this, 'filter_posts_results' ), 10, 2 );\n add_filter( 'the_posts', array( $this, 'filter_the_posts' ), 10, 2 );\n }\n\n public function filter_posts_results( array $posts, WP_Query $query ) {\n $this->posts = []; // Reset posts array for each WP_Query instance\n if ( $query->is_preview ) {\n $this->posts = $posts;\n }\n return $posts;\n }\n\n public function filter_the_posts( array $posts, WP_Query $query ) {\n if ( ! empty( $this->posts ) && current_user_can( 'edit_posts' ) ) {\n $posts = $this->posts;\n }\n return $posts;\n }\n\n}\n\nnew wpse_196050;\n</code></pre>\n"
},
{
"answer_id": 299479,
"author": "Horakiri Suo",
"author_id": 140561,
"author_profile": "https://wordpress.stackexchange.com/users/140561",
"pm_score": 2,
"selected": false,
"text": "<p>Using a custom plugin, and based off <a href=\"https://wordpress.stackexchange.com/questions/299049/allow-contributor-to-view-own-scheduled-post/299478#299478\">this</a> answer:</p>\n\n<pre><code>//allow post preview if you are the post owner, whatever role you might have (e.g. contributor)\nfunction jv_change_post( $posts ) {\n if(is_preview() && !empty($posts)){\n if(user_can('contributor')) \n $posts[0]->post_status = 'publish';\n }\n\n return $posts;\n}\nadd_filter( 'posts_results', 'jv_change_post', 10, 2 );\n</code></pre>\n\n<p>This basically makes 'future' posts pretend like they're already published (but only in the context of the current query), which makes it possible for the contributor to view them.</p>\n"
}
] |
2015/07/29
|
[
"https://wordpress.stackexchange.com/questions/196055",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/18051/"
] |
I have a list of products in WooCommerce that have titles like so:
***Please note: The "groups" are just for myself, they are not categories etc. All products are the same type of product, just two types of products have different codes (Z and UK)***
**"Group 1" -** Unique numbers
* 5000
* 4999
* 4998
* 4997
* 4996
* etc etc
**"Group 2" -** Unique numbers that begin with a **Z**
* Z5000
* Z4999
* Z4998
* Z4997
* Z4996
* etc etc
**"Group 3" -** Unique numbers that begin with **UK**
* UK5000
* UK4999
* UK4998
* UK4997
* UK4996
* etc etc
Obviously by default, WordPress orders by date so on the product's archive page, they look like this:
* UK4020
* 2122
* Z3122
* 4999
* UK1001
* etc etc
What I would like (but can't seem to find any answer with my Google-fu), is to custom order my products like so:
* **Unique numbers, in descending order**
* **Unique numbers that begin with Z, in descending order**
* **Unique numbers that begin with UK, in descending order**
... So my products look like this:
* 5000,
* 4999,
* etc
* Z5000,
* Z4999,
* etc
* UK5000,
* UK4999
* etc
Hope the above makes sense!
|
Unfortunately, WordPress doesn't use a separate capability for previewing posts. A user needs the ability to *edit* a post in order to preview it. As seen in [the WP\_Query::get\_posts() method](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/query.php#L3549):
```
// User must have edit permissions on the draft to preview.
if ( ! current_user_can($edit_cap, $this->posts[0]->ID) ) {
$this->posts = array();
}
```
What you could do is use a combination of the `posts_results` filter (which is applied before unpublished posts are handled) and the `the_posts` filter (which is applied after), to re-populate the posts array if the user is a Contributor.
Please double-check this for any security implications of allowing lower level users access to preview unpublished content.
Untested example:
```
class wpse_196050 {
protected $posts = array();
public function __construct() {
add_filter( 'posts_results', array( $this, 'filter_posts_results' ), 10, 2 );
add_filter( 'the_posts', array( $this, 'filter_the_posts' ), 10, 2 );
}
public function filter_posts_results( array $posts, WP_Query $query ) {
$this->posts = []; // Reset posts array for each WP_Query instance
if ( $query->is_preview ) {
$this->posts = $posts;
}
return $posts;
}
public function filter_the_posts( array $posts, WP_Query $query ) {
if ( ! empty( $this->posts ) && current_user_can( 'edit_posts' ) ) {
$posts = $this->posts;
}
return $posts;
}
}
new wpse_196050;
```
|
196,061 |
<p>I am using WooCommerce in WordPress. I have few categories of products like these, </p>
<p><strong>Example:</strong> </p>
<pre><code>Product 1 Category (//parent)
-- Category 1
-- Category 2
-- Category 3
-- Category 4
Product 2 Category (//parent)
-- Category 10
-- Category 11
-- Category 12
-- Category 13
</code></pre>
<p>If I am in a archive page for Category 2(sub) How can I get all other category name under the parent category (Product 1 Category) as a list.</p>
<p>what i'm trying </p>
<pre><code>$args = array(
'hierarchical' => 1,
'show_option_none' => '',
'hide_empty' => 0,
'parent' => $parent_cat_ID,
'taxonomy' => 'product_cat'
);
$subcats = get_categories($args);
echo '<ul class="wooc_sclist">';
foreach ($subcats as $sc) {
$link = get_term_link( $sc->slug, $sc->taxonomy );
echo '<li><a href="'. $link .'">'.$sc->name.'</a></li>';
}
echo '</ul>';
}
</code></pre>
<p><strong>Out put should :</strong></p>
<pre><code>.Category 1
.Category 2
.Category 3
.Category 4
</code></pre>
<p>I have use below code which works fine in single-product.php page -</p>
<pre><code><?php
$parent = get_category_parents( $cat, true, ' &raquo; ' );
echo $product->get_categories( ', ', '<span>' . _n( 'Category:', 'Categories:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '.</span>' );
?>
</code></pre>
|
[
{
"answer_id": 196209,
"author": "John Blackbourn",
"author_id": 27051,
"author_profile": "https://wordpress.stackexchange.com/users/27051",
"pm_score": 2,
"selected": false,
"text": "<p>Unfortunately, WordPress doesn't use a separate capability for previewing posts. A user needs the ability to <em>edit</em> a post in order to preview it. As seen in <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/query.php#L3549\" rel=\"nofollow noreferrer\">the WP_Query::get_posts() method</a>:</p>\n\n<pre><code>// User must have edit permissions on the draft to preview.\nif ( ! current_user_can($edit_cap, $this->posts[0]->ID) ) {\n $this->posts = array();\n}\n</code></pre>\n\n<p>What you could do is use a combination of the <code>posts_results</code> filter (which is applied before unpublished posts are handled) and the <code>the_posts</code> filter (which is applied after), to re-populate the posts array if the user is a Contributor.</p>\n\n<p>Please double-check this for any security implications of allowing lower level users access to preview unpublished content.</p>\n\n<p>Untested example:</p>\n\n<pre><code>class wpse_196050 {\n\n protected $posts = array();\n\n public function __construct() {\n add_filter( 'posts_results', array( $this, 'filter_posts_results' ), 10, 2 );\n add_filter( 'the_posts', array( $this, 'filter_the_posts' ), 10, 2 );\n }\n\n public function filter_posts_results( array $posts, WP_Query $query ) {\n $this->posts = []; // Reset posts array for each WP_Query instance\n if ( $query->is_preview ) {\n $this->posts = $posts;\n }\n return $posts;\n }\n\n public function filter_the_posts( array $posts, WP_Query $query ) {\n if ( ! empty( $this->posts ) && current_user_can( 'edit_posts' ) ) {\n $posts = $this->posts;\n }\n return $posts;\n }\n\n}\n\nnew wpse_196050;\n</code></pre>\n"
},
{
"answer_id": 299479,
"author": "Horakiri Suo",
"author_id": 140561,
"author_profile": "https://wordpress.stackexchange.com/users/140561",
"pm_score": 2,
"selected": false,
"text": "<p>Using a custom plugin, and based off <a href=\"https://wordpress.stackexchange.com/questions/299049/allow-contributor-to-view-own-scheduled-post/299478#299478\">this</a> answer:</p>\n\n<pre><code>//allow post preview if you are the post owner, whatever role you might have (e.g. contributor)\nfunction jv_change_post( $posts ) {\n if(is_preview() && !empty($posts)){\n if(user_can('contributor')) \n $posts[0]->post_status = 'publish';\n }\n\n return $posts;\n}\nadd_filter( 'posts_results', 'jv_change_post', 10, 2 );\n</code></pre>\n\n<p>This basically makes 'future' posts pretend like they're already published (but only in the context of the current query), which makes it possible for the contributor to view them.</p>\n"
}
] |
2015/07/29
|
[
"https://wordpress.stackexchange.com/questions/196061",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74748/"
] |
I am using WooCommerce in WordPress. I have few categories of products like these,
**Example:**
```
Product 1 Category (//parent)
-- Category 1
-- Category 2
-- Category 3
-- Category 4
Product 2 Category (//parent)
-- Category 10
-- Category 11
-- Category 12
-- Category 13
```
If I am in a archive page for Category 2(sub) How can I get all other category name under the parent category (Product 1 Category) as a list.
what i'm trying
```
$args = array(
'hierarchical' => 1,
'show_option_none' => '',
'hide_empty' => 0,
'parent' => $parent_cat_ID,
'taxonomy' => 'product_cat'
);
$subcats = get_categories($args);
echo '<ul class="wooc_sclist">';
foreach ($subcats as $sc) {
$link = get_term_link( $sc->slug, $sc->taxonomy );
echo '<li><a href="'. $link .'">'.$sc->name.'</a></li>';
}
echo '</ul>';
}
```
**Out put should :**
```
.Category 1
.Category 2
.Category 3
.Category 4
```
I have use below code which works fine in single-product.php page -
```
<?php
$parent = get_category_parents( $cat, true, ' » ' );
echo $product->get_categories( ', ', '<span>' . _n( 'Category:', 'Categories:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '.</span>' );
?>
```
|
Unfortunately, WordPress doesn't use a separate capability for previewing posts. A user needs the ability to *edit* a post in order to preview it. As seen in [the WP\_Query::get\_posts() method](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/query.php#L3549):
```
// User must have edit permissions on the draft to preview.
if ( ! current_user_can($edit_cap, $this->posts[0]->ID) ) {
$this->posts = array();
}
```
What you could do is use a combination of the `posts_results` filter (which is applied before unpublished posts are handled) and the `the_posts` filter (which is applied after), to re-populate the posts array if the user is a Contributor.
Please double-check this for any security implications of allowing lower level users access to preview unpublished content.
Untested example:
```
class wpse_196050 {
protected $posts = array();
public function __construct() {
add_filter( 'posts_results', array( $this, 'filter_posts_results' ), 10, 2 );
add_filter( 'the_posts', array( $this, 'filter_the_posts' ), 10, 2 );
}
public function filter_posts_results( array $posts, WP_Query $query ) {
$this->posts = []; // Reset posts array for each WP_Query instance
if ( $query->is_preview ) {
$this->posts = $posts;
}
return $posts;
}
public function filter_the_posts( array $posts, WP_Query $query ) {
if ( ! empty( $this->posts ) && current_user_can( 'edit_posts' ) ) {
$posts = $this->posts;
}
return $posts;
}
}
new wpse_196050;
```
|
196,109 |
<p>I added custom post type and I have first problem. </p>
<p>I don't know why but if I use <code>$post->ID</code>, independently of post ID it always gave me the same value. I'm using this function <code><?php the_post(); ?></code> to display content of post. What can I do with it?</p>
|
[
{
"answer_id": 196114,
"author": "inverted_index",
"author_id": 71448,
"author_profile": "https://wordpress.stackexchange.com/users/71448",
"pm_score": 1,
"selected": false,
"text": "<p>Use the following before <code>$post->ID</code> in your code:</p>\n\n<pre><code>global $post\n</code></pre>\n"
},
{
"answer_id": 196119,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>When you call <code>the_post</code>, it sets the value of <code>$post</code>, and will do so every time you call it. They give you the same value because they are the <strong>same</strong> object, they aren't separate.</p>\n\n<p>Your linked to code is missing most of your main loop, and also lacks a <code>wp_reset_postdata</code> to cleanup at the end of your WP_Query loop</p>\n"
},
{
"answer_id": 196129,
"author": "stackers",
"author_id": 41012,
"author_profile": "https://wordpress.stackexchange.com/users/41012",
"pm_score": 0,
"selected": false,
"text": "<p>you need to set the global variable for this.and then use this code $post->ID it will work for you.</p>\n\n<pre><code> global $post\n</code></pre>\n"
}
] |
2015/07/30
|
[
"https://wordpress.stackexchange.com/questions/196109",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77009/"
] |
I added custom post type and I have first problem.
I don't know why but if I use `$post->ID`, independently of post ID it always gave me the same value. I'm using this function `<?php the_post(); ?>` to display content of post. What can I do with it?
|
Use the following before `$post->ID` in your code:
```
global $post
```
|
196,126 |
<p>I've figured out how to do something BEFORE sending the mail, but I also need an action to happen AFTER it's been send.</p>
<p>I tried <code>wpcf7_after_send_mail</code> but with no success...</p>
<p>Any help on the matter would be much appreciated.</p>
|
[
{
"answer_id": 196132,
"author": "Menno van der Krift",
"author_id": 76984,
"author_profile": "https://wordpress.stackexchange.com/users/76984",
"pm_score": 4,
"selected": true,
"text": "<p><strong>EDIT:</strong> </p>\n\n<p>Please note that as of 2017 <a href=\"https://contactform7.com/2017/06/07/on-sent-ok-is-deprecated/\" rel=\"nofollow noreferrer\">'on_sent_ok' is deprecated</a>. This means that your code will stop working at some point in the future (likely by the end of 2017). The recommended solution is using DOM event listeners directly. For example, if you used:</p>\n\n<pre><code>on_sent_ok: \"ga( 'send', 'event', 'Contact Form', 'submit' );\"\n</code></pre>\n\n<p>You should replace it with:</p>\n\n<pre><code>document.addEventListener( 'wpcf7mailsent', function( event ) {\n ga( 'send', 'event', 'Contact Form', 'submit' );\n}, false );\n</code></pre>\n\n<p>The JavaScript code can be placed e.g. in the footer of your page.</p>\n\n<p><strong>ORIGINAL ANSWER:</strong></p>\n\n<p>Ok figured it out. In the specific form settings, go to the additional fields tab. Type in the following:\n<code>on_sent_ok: \"location.replace('http://www.website-redirect.com');\"</code><br></p>\n\n<p>It's working like a charm for me now. Hope this helps other developers in the future as well.</p>\n\n<p><a href=\"https://i.stack.imgur.com/TZ12H.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TZ12H.png\" alt=\"enter image description here\"></a></p>\n\n<p>I know the image is in Dutch ... but you can't miss it with the <strong>big red lines</strong> around the tab name.</p>\n"
},
{
"answer_id": 196316,
"author": "buzztone",
"author_id": 27750,
"author_profile": "https://wordpress.stackexchange.com/users/27750",
"pm_score": 2,
"selected": false,
"text": "<p>Using on_sent_ok as explained at <a href=\"http://contactform7.com/additional-settings/\" rel=\"nofollow\">contactform7.com/additional-settings</a> can be very useful for adding some simple JavaScript like <a href=\"http://contactform7.com/redirecting-to-another-url-after-submissions/\" rel=\"nofollow\">redirecting to another page</a>.</p>\n\n<p>However it is rather prone to failing due to Javascript conflicts with either your current WordPress theme or one of the other plugins you are using.</p>\n\n<p>on_sent_ok is the absolutely last thing that runs in Contact Form 7, so any interferring Javascript Conflict can stop this completing.</p>\n\n<p>As an alternative, Contact Form 7 has a large number of hooks which are listed at <a href=\"http://hookr.io/plugins/contact-form-7/\" rel=\"nofollow\">http://hookr.io/plugins/contact-form-7/</a>. These can provide a better targeted, more robust solution.</p>\n"
},
{
"answer_id": 251413,
"author": "adamtomat",
"author_id": 957,
"author_profile": "https://wordpress.stackexchange.com/users/957",
"pm_score": 4,
"selected": false,
"text": "<p>For anybody still landing here looking for a way to run some PHP code after the email has been sent, Contact Form 7 has a <code>wpcf7_mail_sent</code> hook for exactly this. Usage looks a little like:</p>\n\n<pre><code>// ...in functions.php\nadd_action('wpcf7_mail_sent', function ($cf7) {\n // Run code after the email has been sent\n});\n</code></pre>\n\n<p>There is also <code>wpcf7_mail_failed</code>, which lets you hook into when the email fails.</p>\n"
}
] |
2015/07/30
|
[
"https://wordpress.stackexchange.com/questions/196126",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76984/"
] |
I've figured out how to do something BEFORE sending the mail, but I also need an action to happen AFTER it's been send.
I tried `wpcf7_after_send_mail` but with no success...
Any help on the matter would be much appreciated.
|
**EDIT:**
Please note that as of 2017 ['on\_sent\_ok' is deprecated](https://contactform7.com/2017/06/07/on-sent-ok-is-deprecated/). This means that your code will stop working at some point in the future (likely by the end of 2017). The recommended solution is using DOM event listeners directly. For example, if you used:
```
on_sent_ok: "ga( 'send', 'event', 'Contact Form', 'submit' );"
```
You should replace it with:
```
document.addEventListener( 'wpcf7mailsent', function( event ) {
ga( 'send', 'event', 'Contact Form', 'submit' );
}, false );
```
The JavaScript code can be placed e.g. in the footer of your page.
**ORIGINAL ANSWER:**
Ok figured it out. In the specific form settings, go to the additional fields tab. Type in the following:
`on_sent_ok: "location.replace('http://www.website-redirect.com');"`
It's working like a charm for me now. Hope this helps other developers in the future as well.
[](https://i.stack.imgur.com/TZ12H.png)
I know the image is in Dutch ... but you can't miss it with the **big red lines** around the tab name.
|
196,147 |
<p>When I make click at any file from my website, the URL displays like: </p>
<p><strong>www.mywebsite.com/index.php/about-me</strong> OR <strong>www.mywebsite.com/index.php/references</strong> </p>
<p>I just want to know if it is normal that index.php gets always displayed before any other file (something like <strong>www.mywebsite.com/about-me</strong> would be more common to see) or if this is some type of error. </p>
|
[
{
"answer_id": 196174,
"author": "feelinferrety",
"author_id": 48824,
"author_profile": "https://wordpress.stackexchange.com/users/48824",
"pm_score": 2,
"selected": true,
"text": "<p>First, check if you have an .htaccess file with the following:</p>\n\n<pre><code># BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n# END WordPress\n</code></pre>\n\n<p>If this file already exists with the appropriate rules, try the following:</p>\n\n<ul>\n<li>Go to your site Settings > Permalinks. If there is something already there, make sure you copy it and keep it safe in case it breaks your site. Select one of the defaults and save.</li>\n<li>Visit your site and refresh.</li>\n<li>If you still have no solution, try a hard refresh on your site - <code>cmd/ctrl + shift + r</code>.</li>\n</ul>\n\n<p>If you are still having the problem, please go into more detail about the circumstances of your site (version, plugins, theme, etc.) so we can try to better help you.</p>\n"
},
{
"answer_id": 196183,
"author": "cp_miramar",
"author_id": 76652,
"author_profile": "https://wordpress.stackexchange.com/users/76652",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks to the suggestions of @feelinferrety I was able to put the URLs from my website as <strong>www.mywebsite.com/index.php/about-me</strong> OR <strong>www.mywebsite.com/index.php/references</strong>. \nJust did the following: </p>\n\n<p>Go to your site Settings > Permalinks > Common settings: Select the option Postname. </p>\n"
}
] |
2015/07/30
|
[
"https://wordpress.stackexchange.com/questions/196147",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76652/"
] |
When I make click at any file from my website, the URL displays like:
**www.mywebsite.com/index.php/about-me** OR **www.mywebsite.com/index.php/references**
I just want to know if it is normal that index.php gets always displayed before any other file (something like **www.mywebsite.com/about-me** would be more common to see) or if this is some type of error.
|
First, check if you have an .htaccess file with the following:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
If this file already exists with the appropriate rules, try the following:
* Go to your site Settings > Permalinks. If there is something already there, make sure you copy it and keep it safe in case it breaks your site. Select one of the defaults and save.
* Visit your site and refresh.
* If you still have no solution, try a hard refresh on your site - `cmd/ctrl + shift + r`.
If you are still having the problem, please go into more detail about the circumstances of your site (version, plugins, theme, etc.) so we can try to better help you.
|
196,159 |
<p>I've got a Category Archive page with name <code>category-slugb.php</code>.</p>
<p>I have a sidebar with some Widget Logic that uses <code>in_category('category-sluga')</code>.</p>
<p>What's odd is that on this Category Archive page (i.e. for all Posts of <code>category-slugb.php</code>) the <code>in_category('category-sluga')</code> condition is being triggered as <code>true</code>.</p>
<p>Why? Is there something I'm doing wrong here?</p>
<p>Basically, I do not want the sidebar that has the <code>in_category('category-sluga')</code> Widget Logic to appear on the <code>category-slugb.php</code> Category Archive Page.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 196174,
"author": "feelinferrety",
"author_id": 48824,
"author_profile": "https://wordpress.stackexchange.com/users/48824",
"pm_score": 2,
"selected": true,
"text": "<p>First, check if you have an .htaccess file with the following:</p>\n\n<pre><code># BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n# END WordPress\n</code></pre>\n\n<p>If this file already exists with the appropriate rules, try the following:</p>\n\n<ul>\n<li>Go to your site Settings > Permalinks. If there is something already there, make sure you copy it and keep it safe in case it breaks your site. Select one of the defaults and save.</li>\n<li>Visit your site and refresh.</li>\n<li>If you still have no solution, try a hard refresh on your site - <code>cmd/ctrl + shift + r</code>.</li>\n</ul>\n\n<p>If you are still having the problem, please go into more detail about the circumstances of your site (version, plugins, theme, etc.) so we can try to better help you.</p>\n"
},
{
"answer_id": 196183,
"author": "cp_miramar",
"author_id": 76652,
"author_profile": "https://wordpress.stackexchange.com/users/76652",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks to the suggestions of @feelinferrety I was able to put the URLs from my website as <strong>www.mywebsite.com/index.php/about-me</strong> OR <strong>www.mywebsite.com/index.php/references</strong>. \nJust did the following: </p>\n\n<p>Go to your site Settings > Permalinks > Common settings: Select the option Postname. </p>\n"
}
] |
2015/07/30
|
[
"https://wordpress.stackexchange.com/questions/196159",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48904/"
] |
I've got a Category Archive page with name `category-slugb.php`.
I have a sidebar with some Widget Logic that uses `in_category('category-sluga')`.
What's odd is that on this Category Archive page (i.e. for all Posts of `category-slugb.php`) the `in_category('category-sluga')` condition is being triggered as `true`.
Why? Is there something I'm doing wrong here?
Basically, I do not want the sidebar that has the `in_category('category-sluga')` Widget Logic to appear on the `category-slugb.php` Category Archive Page.
Any suggestions?
|
First, check if you have an .htaccess file with the following:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
If this file already exists with the appropriate rules, try the following:
* Go to your site Settings > Permalinks. If there is something already there, make sure you copy it and keep it safe in case it breaks your site. Select one of the defaults and save.
* Visit your site and refresh.
* If you still have no solution, try a hard refresh on your site - `cmd/ctrl + shift + r`.
If you are still having the problem, please go into more detail about the circumstances of your site (version, plugins, theme, etc.) so we can try to better help you.
|
196,186 |
<p>Does anyone know how to display the <a href="https://codex.wordpress.org/Template_Tags/wp_list_categories" rel="nofollow"><code>wp_list_categories()</code></a> on a <code>div</code> instead of the <code>li</code>?</p>
<p>I basically want to wrap main categories and its children in a bootstrap column.</p>
<pre><code>$args = array(
'taxonomy' => 'product_category',
'hide_empty' => 0,
'orderby' => 'name',
'order' => 'ASC',
'show_count' => 0,
'use_desc_for_title' => 0,
'title_li' => 0
);
wp_list_categories($args);
</code></pre>
|
[
{
"answer_id": 196204,
"author": "John Blackbourn",
"author_id": 27051,
"author_profile": "https://wordpress.stackexchange.com/users/27051",
"pm_score": 3,
"selected": false,
"text": "<p>You can specify the <code>style</code> argument as something other than the default (which is <code>list</code>) and it won't wrap the output in a <code><li></code>. You can then wrap it in a <code><div></code> yourself.</p>\n\n<p>Combine it with the <code>echo</code> argument if you need to check that the list isn't empty. Example:</p>\n\n<pre><code>$args = array(\n 'taxonomy' => 'product_category',\n 'hide_empty' => 0,\n 'orderby' => 'name',\n 'order' => 'ASC',\n 'show_count' => 0,\n 'use_desc_for_title' => 0,\n 'title_li' => 0,\n 'style' => '',\n 'echo' => false,\n);\n$categories = wp_list_categories($args);\n\nif ( $categories ) {\n printf( '<div class=\"col\">%s</div>', $categories );\n}\n</code></pre>\n"
},
{
"answer_id": 196259,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 2,
"selected": false,
"text": "<p>Please add two new argument into your <code>$args</code> array. </p>\n\n<p>1) Style with none value. See the markup section for <a href=\"https://codex.wordpress.org/Template_Tags/wp_list_categories#Markup_and_Styling_of_Category_Lists\" rel=\"nofollow\">more</a>.\n2) echo with 0(False).</p>\n\n<p>Now call and store the result into <code>$categories</code> variable and print it via <code>printf()</code>.</p>\n\n<p>Final code like:</p>\n\n<pre><code>$args = array(\n 'taxonomy' => 'product_category',\n 'hide_empty' => 0,\n 'orderby' => 'name',\n 'order' => 'ASC',\n 'show_count' => 0,\n 'use_desc_for_title' => 0,\n 'title_li' => 0,\n 'style' => 'none',\n 'echo' => 0,\n);\n\n$categories = wp_list_categories($args);\nif ( $categories ) {\n printf( '<div>%s</div>', $categories );\n}\n</code></pre>\n\n<p>In aditional, you can use <code>if ( !preg_match( '/No\\scategories/i', $cats ) )</code> If the displayed text reads \"No categories\".</p>\n\n<p>P.S. If this stuff helps you please leave me a comment and support :)</p>\n"
}
] |
2015/07/30
|
[
"https://wordpress.stackexchange.com/questions/196186",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77053/"
] |
Does anyone know how to display the [`wp_list_categories()`](https://codex.wordpress.org/Template_Tags/wp_list_categories) on a `div` instead of the `li`?
I basically want to wrap main categories and its children in a bootstrap column.
```
$args = array(
'taxonomy' => 'product_category',
'hide_empty' => 0,
'orderby' => 'name',
'order' => 'ASC',
'show_count' => 0,
'use_desc_for_title' => 0,
'title_li' => 0
);
wp_list_categories($args);
```
|
You can specify the `style` argument as something other than the default (which is `list`) and it won't wrap the output in a `<li>`. You can then wrap it in a `<div>` yourself.
Combine it with the `echo` argument if you need to check that the list isn't empty. Example:
```
$args = array(
'taxonomy' => 'product_category',
'hide_empty' => 0,
'orderby' => 'name',
'order' => 'ASC',
'show_count' => 0,
'use_desc_for_title' => 0,
'title_li' => 0,
'style' => '',
'echo' => false,
);
$categories = wp_list_categories($args);
if ( $categories ) {
printf( '<div class="col">%s</div>', $categories );
}
```
|
196,191 |
<p>I have code like this:</p>
<pre><code><?php echo '<div class="class-name">' . __( 'Text','text-domain' ) . '</div>'; ?>
</code></pre>
<p>in a plugin of mine.</p>
<p>Do i have to escape this? (esc_html or similiar)?</p>
|
[
{
"answer_id": 196200,
"author": "jdm2112",
"author_id": 45202,
"author_profile": "https://wordpress.stackexchange.com/users/45202",
"pm_score": -1,
"selected": false,
"text": "<p>No. The contents of your <code>echo</code> statement will be output to the browser with no problems.</p>\n"
},
{
"answer_id": 196201,
"author": "John Blackbourn",
"author_id": 27051,
"author_profile": "https://wordpress.stackexchange.com/users/27051",
"pm_score": 1,
"selected": false,
"text": "<p>The answer typically depends on where your translations come from. WordPress core doesn't usually escape strings such as this, but you may wish to do so in your plugin.</p>\n\n<p>A translation might come from an \"untrusted\" source and could, in theory, contain malicious JavaScript, and escaping would protect you from this. In reality that's unlikely, but escaping this text does add another layer of hardening. I've started escaping strings such as this in my plugins recently.</p>\n\n<p>In addition, using escaping functions around strings such as this means your code will pass the WordPress Code Standards sniffers.</p>\n"
},
{
"answer_id": 196270,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 0,
"selected": false,
"text": "<p>No. There is no user supplied data in that string. You only have to escape user supplied data. The only why this could be hacked would be if someone managed to push something nasty through the <code>__()</code> function but that would mean a server level hack, if possible at all, and if that were the case no escaping is going to fix anything. With that kind of hack, the attacker can do virtually anything.</p>\n"
}
] |
2015/07/30
|
[
"https://wordpress.stackexchange.com/questions/196191",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77057/"
] |
I have code like this:
```
<?php echo '<div class="class-name">' . __( 'Text','text-domain' ) . '</div>'; ?>
```
in a plugin of mine.
Do i have to escape this? (esc\_html or similiar)?
|
The answer typically depends on where your translations come from. WordPress core doesn't usually escape strings such as this, but you may wish to do so in your plugin.
A translation might come from an "untrusted" source and could, in theory, contain malicious JavaScript, and escaping would protect you from this. In reality that's unlikely, but escaping this text does add another layer of hardening. I've started escaping strings such as this in my plugins recently.
In addition, using escaping functions around strings such as this means your code will pass the WordPress Code Standards sniffers.
|
196,231 |
<p>I have errors in WordPress:</p>
<blockquote>
<p>PHP Notice: Undefined offset: 0 in
/home/userpro/public_html/wp-content/themes/hoon/inc/tweaks.php on
line 602</p>
<p>PHP Notice: Trying to get property of non-object in
/home/userpro/public_html/wp-content/themes/hoon/inc/tweaks.php on
line 602</p>
</blockquote>
<p>Code:</p>
<pre><code>/**
* Display Future Posts
*
* Display future post in the events category to all users.
*/
function hoon_show_all_future_posts( $posts ) {
global $wp_query, $wpdb;
if ( is_single() && $wp_query->post_count == 0 ) {
$events_cat = hoon_option( 'events_category' );
$request = $wpdb->get_results( $wp_query->request );
/* Line 602 bellow */
if ( post_is_in_descendant_category( $events_cat, $request[0]->ID ) || in_category( $events_cat, $request[0]->ID ) ) {
$posts = $request;
}
}
return $posts;
}
add_filter( 'the_posts', 'hoon_show_all_future_posts' );
</code></pre>
|
[
{
"answer_id": 196236,
"author": "websupporter",
"author_id": 48693,
"author_profile": "https://wordpress.stackexchange.com/users/48693",
"pm_score": 1,
"selected": false,
"text": "<p>If <code>$wp_query->post_count == 0</code> I cant see how <code>$wpdb->get_results( $wp_query->request )</code> would return any posts. So basically </p>\n\n<pre><code>$request = $wpdb->get_results( $wp_query->request );\n</code></pre>\n\n<p>contains nothing and <code>$request[0]</code> doesn't exist.\nErgo</p>\n\n<pre><code>PHP Notice: Undefined offset: 0\n</code></pre>\n\n<p>It would be interesting to know, what this could is supposed to achieve.</p>\n"
},
{
"answer_id": 196246,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 0,
"selected": false,
"text": "<p>The first error message is for undefined variable which you used <code>$request[0]</code> and second one is for <code>$request</code> is not a object so you cannot use as object.</p>\n\n<p>I suggest you that use below code and check what you missed:</p>\n\n<pre><code>$request = $wpdb->get_results( $wp_query->request );\nprint('<pre>');\nprint_r($request);\nprint('</pre>'); exit;\n</code></pre>\n\n<p>Above code shows what <code>$request</code> contains.</p>\n\n<p>Let me know if you face any query regarding this OR require more help.</p>\n"
}
] |
2015/07/31
|
[
"https://wordpress.stackexchange.com/questions/196231",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77073/"
] |
I have errors in WordPress:
>
> PHP Notice: Undefined offset: 0 in
> /home/userpro/public\_html/wp-content/themes/hoon/inc/tweaks.php on
> line 602
>
>
> PHP Notice: Trying to get property of non-object in
> /home/userpro/public\_html/wp-content/themes/hoon/inc/tweaks.php on
> line 602
>
>
>
Code:
```
/**
* Display Future Posts
*
* Display future post in the events category to all users.
*/
function hoon_show_all_future_posts( $posts ) {
global $wp_query, $wpdb;
if ( is_single() && $wp_query->post_count == 0 ) {
$events_cat = hoon_option( 'events_category' );
$request = $wpdb->get_results( $wp_query->request );
/* Line 602 bellow */
if ( post_is_in_descendant_category( $events_cat, $request[0]->ID ) || in_category( $events_cat, $request[0]->ID ) ) {
$posts = $request;
}
}
return $posts;
}
add_filter( 'the_posts', 'hoon_show_all_future_posts' );
```
|
If `$wp_query->post_count == 0` I cant see how `$wpdb->get_results( $wp_query->request )` would return any posts. So basically
```
$request = $wpdb->get_results( $wp_query->request );
```
contains nothing and `$request[0]` doesn't exist.
Ergo
```
PHP Notice: Undefined offset: 0
```
It would be interesting to know, what this could is supposed to achieve.
|
196,232 |
<p>I have a very simple function to create a shortcode to get the name of my page. I was using this shortcode in a form, but WordPress changed the Shortcode API and that no longer works. So I was wondering if I could use a second function to make a shortcode that would put in the HTML plus the result of the first shortcode?</p>
<p>This is what I have at the moment...</p>
<pre><code>function my_title( ){
return get_the_title();
}
add_shortcode( 'page_title', 'my_title' );
</code></pre>
<p>and then in the page I have this html...</p>
<pre><code><input type=hidden name=itemname value='[page_title] small print'>
</code></pre>
<p>Can I make a new function that will have the input field plus the page title as a shortcode so I can replace the whole input field with a shortcode? Apologies is this sounds odd, I'm a total newbie at this!</p>
|
[
{
"answer_id": 196236,
"author": "websupporter",
"author_id": 48693,
"author_profile": "https://wordpress.stackexchange.com/users/48693",
"pm_score": 1,
"selected": false,
"text": "<p>If <code>$wp_query->post_count == 0</code> I cant see how <code>$wpdb->get_results( $wp_query->request )</code> would return any posts. So basically </p>\n\n<pre><code>$request = $wpdb->get_results( $wp_query->request );\n</code></pre>\n\n<p>contains nothing and <code>$request[0]</code> doesn't exist.\nErgo</p>\n\n<pre><code>PHP Notice: Undefined offset: 0\n</code></pre>\n\n<p>It would be interesting to know, what this could is supposed to achieve.</p>\n"
},
{
"answer_id": 196246,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 0,
"selected": false,
"text": "<p>The first error message is for undefined variable which you used <code>$request[0]</code> and second one is for <code>$request</code> is not a object so you cannot use as object.</p>\n\n<p>I suggest you that use below code and check what you missed:</p>\n\n<pre><code>$request = $wpdb->get_results( $wp_query->request );\nprint('<pre>');\nprint_r($request);\nprint('</pre>'); exit;\n</code></pre>\n\n<p>Above code shows what <code>$request</code> contains.</p>\n\n<p>Let me know if you face any query regarding this OR require more help.</p>\n"
}
] |
2015/07/31
|
[
"https://wordpress.stackexchange.com/questions/196232",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77075/"
] |
I have a very simple function to create a shortcode to get the name of my page. I was using this shortcode in a form, but WordPress changed the Shortcode API and that no longer works. So I was wondering if I could use a second function to make a shortcode that would put in the HTML plus the result of the first shortcode?
This is what I have at the moment...
```
function my_title( ){
return get_the_title();
}
add_shortcode( 'page_title', 'my_title' );
```
and then in the page I have this html...
```
<input type=hidden name=itemname value='[page_title] small print'>
```
Can I make a new function that will have the input field plus the page title as a shortcode so I can replace the whole input field with a shortcode? Apologies is this sounds odd, I'm a total newbie at this!
|
If `$wp_query->post_count == 0` I cant see how `$wpdb->get_results( $wp_query->request )` would return any posts. So basically
```
$request = $wpdb->get_results( $wp_query->request );
```
contains nothing and `$request[0]` doesn't exist.
Ergo
```
PHP Notice: Undefined offset: 0
```
It would be interesting to know, what this could is supposed to achieve.
|
196,289 |
<p>Click on "Pages" -> Click on "Add New"</p>
<p>In the add new page screen. The default page template selected is "Default Template". Is there a way to change the default option to, let's say "My Other Template". So that when I click on "Add New", "My Other Template" will always be selected by default? This needs to be done before the page is saved. I can accomplish this with JS. Is there a WP option?</p>
<p><strong>UPDATE:</strong></p>
<p>Here's an example:</p>
<p>Template Options:</p>
<ul>
<li>Default Template (automatically selected)</li>
<li>My Template 1</li>
<li>My Template 2</li>
</ul>
<p>Is there a WordPress way to change to:</p>
<ul>
<li>Default Template</li>
<li>My Template 1 (automatically selected)</li>
<li>My Template 2</li>
</ul>
<p>I thought maybe this could be accomplished with a function:</p>
<pre><code>if (some condition is met)
default_template = My Template 1
endif
</code></pre>
<p>I know how the template hierarchy works. I know how to make my template always be used for certain pages. But that's not the question. I am just trying to make things easier for the end-user so that upon certain conditions I can preselect the template, that should be used on a group of pages, but still, give the user the flexibility to switch back to another template if needed.</p>
|
[
{
"answer_id": 196297,
"author": "czerspalace",
"author_id": 47406,
"author_profile": "https://wordpress.stackexchange.com/users/47406",
"pm_score": 1,
"selected": false,
"text": "<p>I have not tested this, but it may work. The template is chosen based on a value in the global post object, so we need to change that value in the post object before the metabox is rendered. The code which chooses the default dropdown is here: <a href=\"https://core.trac.wordpress.org/browser/trunk/src/wp-admin/includes/meta-boxes.php#L751\" rel=\"nofollow\">https://core.trac.wordpress.org/browser/trunk/src/wp-admin/includes/meta-boxes.php#L751</a></p>\n\n<pre><code>add_action('add_meta_boxes', 'wpse196289_default_page_template', 1);\n\nfunction wpse196289_default_page_template() {\n global $post;\n if ( 'page' == $post->post_type && 0 != count( get_page_templates( $post ) ) && get_option( 'page_for_posts' ) != $post->ID ) {\n if( $my_conditions )\n $post->page_template = \"page-mytemplate.php\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 196319,
"author": "Brad Dalton",
"author_id": 9884,
"author_profile": "https://wordpress.stackexchange.com/users/9884",
"pm_score": 0,
"selected": false,
"text": "<p>Use <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include\" rel=\"nofollow\"><code>template_include</code></a> in your functions file with a conditional tag.</p>\n\n<pre><code>add_filter( 'template_include', 'default_page_template', 99 );\n\nfunction default_page_template( $template ) {\n\n if ( is_singular( 'page' ) ) {\n $default_template = locate_template( array( 'default-page-template.php' ) );\n if ( '' != $default_template ) {\n return $default_template ;\n }\n }\n\n return $template;\n}\n</code></pre>\n"
},
{
"answer_id": 231503,
"author": "Adrian B",
"author_id": 45405,
"author_profile": "https://wordpress.stackexchange.com/users/45405",
"pm_score": 3,
"selected": false,
"text": "<p>Using <code>template_include</code> (as suggested by Brad Dalton) only changes the page template on the front end, not in the admin when editing a page. </p>\n\n<p>On the other hand, changing the value in the post object before the metabox is rendered, as suggested by czerspalace, works! I added a check to only apply this when <code>$post->page_template</code> is not set, like this: </p>\n\n<pre><code>function wpse196289_default_page_template() {\n global $post;\n if ( 'page' == $post->post_type \n && 0 != count( get_page_templates( $post ) ) \n && get_option( 'page_for_posts' ) != $post->ID // Not the page for listing posts\n && '' == $post->page_template // Only when page_template is not set\n ) {\n $post->page_template = \"page-mytemplate.php\";\n }\n}\nadd_action('add_meta_boxes', 'wpse196289_default_page_template', 1);\n</code></pre>\n"
},
{
"answer_id": 279421,
"author": "Ben Matthews",
"author_id": 127471,
"author_profile": "https://wordpress.stackexchange.com/users/127471",
"pm_score": 1,
"selected": false,
"text": "<p>The simplest way that I found, without hacking code is to create a separate page.php (away from your page_template-name.php files) and get_template_part() to redirect to your template file. This then provides the default template across your site, as well as keeping the template as a discrete option.</p>\n\n<pre><code><?php get_template_part('page_template-name'); ?>\n</code></pre>\n\n<p>This is all that needs to exist in your page.php file. It simply gets your default template. If you want to change your template site wide, then you could simply change the slug. Any page that then has the default option selected will change. Any page that is specifically set to use the template (i.e. set to template-1 instead of default), won't change.</p>\n"
},
{
"answer_id": 328272,
"author": "Przemek Maczewski",
"author_id": 68013,
"author_profile": "https://wordpress.stackexchange.com/users/68013",
"pm_score": 1,
"selected": false,
"text": "<p>I've managed to accomplish that in the new <strong>block editor</strong> (Gutenberg). </p>\n\n<p>The task needs a hook into <strong>REST API response</strong> in this case.</p>\n\n<p>I took the conditions from <a href=\"https://wordpress.stackexchange.com/questions/196289/is-there-a-way-to-change-the-default-page-template-selection#answer-231503\">Adrian's</a> answer.</p>\n\n<pre><code>foreach ( array( 'page', 'post' ) as $post_type ) :\n add_filter( \"rest_prepare_{$post_type}\", 'wpse196289_rest_set_default_page_template', 1, 2 );\nendforeach;\n\nfunction wpse196289_rest_set_default_page_template( $data, $post ) {\n if ( 0 != count( get_page_templates( $post ) ) && get_option( 'page_for_posts' ) != $post->ID && '' == $data->data['template'] ) :\n $data->data['template'] = 'page-mytemplate.php';\n endif;\n\n return $data;\n}\n</code></pre>\n"
}
] |
2015/07/31
|
[
"https://wordpress.stackexchange.com/questions/196289",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/30984/"
] |
Click on "Pages" -> Click on "Add New"
In the add new page screen. The default page template selected is "Default Template". Is there a way to change the default option to, let's say "My Other Template". So that when I click on "Add New", "My Other Template" will always be selected by default? This needs to be done before the page is saved. I can accomplish this with JS. Is there a WP option?
**UPDATE:**
Here's an example:
Template Options:
* Default Template (automatically selected)
* My Template 1
* My Template 2
Is there a WordPress way to change to:
* Default Template
* My Template 1 (automatically selected)
* My Template 2
I thought maybe this could be accomplished with a function:
```
if (some condition is met)
default_template = My Template 1
endif
```
I know how the template hierarchy works. I know how to make my template always be used for certain pages. But that's not the question. I am just trying to make things easier for the end-user so that upon certain conditions I can preselect the template, that should be used on a group of pages, but still, give the user the flexibility to switch back to another template if needed.
|
Using `template_include` (as suggested by Brad Dalton) only changes the page template on the front end, not in the admin when editing a page.
On the other hand, changing the value in the post object before the metabox is rendered, as suggested by czerspalace, works! I added a check to only apply this when `$post->page_template` is not set, like this:
```
function wpse196289_default_page_template() {
global $post;
if ( 'page' == $post->post_type
&& 0 != count( get_page_templates( $post ) )
&& get_option( 'page_for_posts' ) != $post->ID // Not the page for listing posts
&& '' == $post->page_template // Only when page_template is not set
) {
$post->page_template = "page-mytemplate.php";
}
}
add_action('add_meta_boxes', 'wpse196289_default_page_template', 1);
```
|
196,304 |
<p>In the example below, <code>$shortcodes</code> is a multidimensional array with shortcode data. </p>
<pre><code>foreach( $shortcodes as $shortcode ) {
// Here we have the shortcode name, could be 'custom_person_john'.
$shortcode_name = $shortcode['slug'];
// Anonymous function should be referred to as 'custom_person_john'.
$shortcode_name = function( $shortcode ) {
// Build shortcode attributes.
$atts = shortcode_atts( array(
'name' => 'john',
'type' => 'mammal'
), $atts );
$markup = '<div class="'.$atts['name'].'">';
$markup .= '<div>';
// $shortcode should contain custom markup from the array.
$markup .= $shortcode['html'];
$markup .= '</div>';
$markup .= '</div>';
return $markup;
};
// Trying to register the shortcode
add_shortcode( $shortcode['slug'], $shortcode_name( $shortcode ) );
};
</code></pre>
<p>So this is not working, but I can't grasps why. If I dump all the registered shortcodes, they don't show up in the list. Trying to load them simple echo's [custom_person_john]. I don't have errors either. </p>
<p>Edit: If anyone has other ideas on how to create them dynamically out of an array, feel free to suggest :)</p>
|
[
{
"answer_id": 196333,
"author": "Mohammad Mursaleen",
"author_id": 35899,
"author_profile": "https://wordpress.stackexchange.com/users/35899",
"pm_score": 1,
"selected": false,
"text": "<p>Few months ago I was working on a similar thing where I had to generate <a href=\"https://codex.wordpress.org/Shortcode\" rel=\"nofollow\">short codes</a> dynamically. But I took a different approach.</p>\n\n<p>What I did was as following;</p>\n\n<ol>\n<li><p>I registered a <a href=\"https://codex.wordpress.org/Shortcode\" rel=\"nofollow\">short code</a> and <a href=\"https://codex.wordpress.org/Post_Types#Custom_Post_Types\" rel=\"nofollow\">custom post type</a> for which I had to use that dynamic <a href=\"https://codex.wordpress.org/Shortcode\" rel=\"nofollow\">short code</a>.</p></li>\n<li><p>Then added <a href=\"https://codex.wordpress.org/Shortcode_API#Handling_Attributes\" rel=\"nofollow\">attribute</a> for <a href=\"http://codex.wordpress.org/Glossary#Post_Slug\" rel=\"nofollow\">post name (slug)</a> in that <a href=\"https://codex.wordpress.org/Shortcode\" rel=\"nofollow\">short code</a> to get data dynamically to display on front end.</p></li>\n</ol>\n\n<p>Here is sample code for how you can do that;</p>\n\n<pre><code>// Shortcode to display html in frontend\n// [dynamic_shortcode name='post-slug']\nfunction dynamic_shortcode( $atts ) {\n\n // Get Attributes\n extract( shortcode_atts(\n array(\n 'name' => '' // DEFAULT SLUG SET TO EMPTY\n ), $atts )\n );\n\n // WP_Query arguments\n $args = array (\n 'name' => $name, // GET POST BY SLUG // IGNORE IF YOU ARE GETTING ERROR ON THIS LINE IN YOUR EDITOR\n 'post_type' => 'your-post-type', // YOUR POST TYPE\n 'post_status' => 'publish', // POST STATUS\n );\n\n\n // The Query\n $query = new WP_Query( $args );\n\n // The Loop\n if ( $query->have_posts() && $name != '' ) {\n while ( $query->have_posts() ) {\n $query->the_post();\n\n $html_src = get_post_meta( get_the_ID() , 'html_src' , true); // GET HTML SOURCE FROM YOUR POST META\n\n if ( $html_src) {\n return $html_src; // RETURN HTML TO DISPLAY ON FRONT END\n }\n\n }\n } else {\n // no posts found\n return '<p style=\"color: red\" >Sorry You have set no html for this slug...</p>';\n\n }\n\n\n// Restore original Post Data\n wp_reset_postdata();\n}\nadd_shortcode( 'dynamic_shortcode', 'dynamic_shortcode' );\n</code></pre>\n\n<p>Hope this might work for you as well.</p>\n"
},
{
"answer_id": 196348,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 4,
"selected": true,
"text": "<p>the shortcodes doesn't shop up in the liste because it's not a valid declaration with a valid function callback on the 2nd argument</p>\n\n<p>try this to see what append : </p>\n\n<pre><code>// shortcode data\n\nadd_filter(\"shortcode_list\", function ($shortcode_list) {\n $shortcode_list[\"slugA\"] = array(\n \"html\" => \"test html 1\",\n );\n\n return $shortcode_list;\n});\n\nadd_filter(\"shortcode_list\", function ($shortcode_list) {\n $shortcode_list[\"slugB\"] = array(\n \"html\" => \"test <strong>html 2 - [slugA]</strong>\",\n );\n\n return $shortcode_list;\n});\n\n\n// shortcodes declaration\n\nadd_action(\"init\", function () {\n\n $shortcodes = apply_filters(\"shortcode_list\", array());\n\n foreach (array_keys($shortcodes) as $shortcode_slug) {\n add_shortcode($shortcode_slug, \"shortcode_callback\");\n };\n\n});\n\n\n// callback function\n\nfunction shortcode_callback($atts, $content = \"\", $tag) {\n\n // Build shortcode attributes.\n $atts = shortcode_atts( array(\n 'name' => 'john',\n 'type' => 'mammal'\n ), $atts);\n\n\n // shortcode data\n $shortcodes = apply_filters(\"shortcode_list\", array());\n $shortcode = $shortcodes[$tag];\n\n\n // construct result of the shortcode\n\n $markup = \"\";\n $markup .= '<div class=\"'.$atts['name'].'\">';\n $markup .= '<div>';\n // $shortcode should contain custom markup from the array.\n $markup .= $shortcode['html'];\n //$markup .= do_shortcode($shortcode['html']); // to replace shortcodes in the \"html\" data\n\n\n $markup .= '<pre>';\n $markup .= print_r($atts, TRUE);\n $markup .= '</pre>';\n\n $markup .= '</div>';\n $markup .= '</div>';\n\n return $markup;\n\n}\n</code></pre>\n"
}
] |
2015/07/31
|
[
"https://wordpress.stackexchange.com/questions/196304",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62241/"
] |
In the example below, `$shortcodes` is a multidimensional array with shortcode data.
```
foreach( $shortcodes as $shortcode ) {
// Here we have the shortcode name, could be 'custom_person_john'.
$shortcode_name = $shortcode['slug'];
// Anonymous function should be referred to as 'custom_person_john'.
$shortcode_name = function( $shortcode ) {
// Build shortcode attributes.
$atts = shortcode_atts( array(
'name' => 'john',
'type' => 'mammal'
), $atts );
$markup = '<div class="'.$atts['name'].'">';
$markup .= '<div>';
// $shortcode should contain custom markup from the array.
$markup .= $shortcode['html'];
$markup .= '</div>';
$markup .= '</div>';
return $markup;
};
// Trying to register the shortcode
add_shortcode( $shortcode['slug'], $shortcode_name( $shortcode ) );
};
```
So this is not working, but I can't grasps why. If I dump all the registered shortcodes, they don't show up in the list. Trying to load them simple echo's [custom\_person\_john]. I don't have errors either.
Edit: If anyone has other ideas on how to create them dynamically out of an array, feel free to suggest :)
|
the shortcodes doesn't shop up in the liste because it's not a valid declaration with a valid function callback on the 2nd argument
try this to see what append :
```
// shortcode data
add_filter("shortcode_list", function ($shortcode_list) {
$shortcode_list["slugA"] = array(
"html" => "test html 1",
);
return $shortcode_list;
});
add_filter("shortcode_list", function ($shortcode_list) {
$shortcode_list["slugB"] = array(
"html" => "test <strong>html 2 - [slugA]</strong>",
);
return $shortcode_list;
});
// shortcodes declaration
add_action("init", function () {
$shortcodes = apply_filters("shortcode_list", array());
foreach (array_keys($shortcodes) as $shortcode_slug) {
add_shortcode($shortcode_slug, "shortcode_callback");
};
});
// callback function
function shortcode_callback($atts, $content = "", $tag) {
// Build shortcode attributes.
$atts = shortcode_atts( array(
'name' => 'john',
'type' => 'mammal'
), $atts);
// shortcode data
$shortcodes = apply_filters("shortcode_list", array());
$shortcode = $shortcodes[$tag];
// construct result of the shortcode
$markup = "";
$markup .= '<div class="'.$atts['name'].'">';
$markup .= '<div>';
// $shortcode should contain custom markup from the array.
$markup .= $shortcode['html'];
//$markup .= do_shortcode($shortcode['html']); // to replace shortcodes in the "html" data
$markup .= '<pre>';
$markup .= print_r($atts, TRUE);
$markup .= '</pre>';
$markup .= '</div>';
$markup .= '</div>';
return $markup;
}
```
|
196,339 |
<p>I am currently using the Minnow theme on Wordpress. I have set my site to show latest posts from my blog, but I have also create a page called 'About'. This page doesn't show up on my site or in the navigation menu and I'm not quite sure how to get this to display. </p>
<p>Would appreciate any help I can get. </p>
<p>Thank you.</p>
|
[
{
"answer_id": 196333,
"author": "Mohammad Mursaleen",
"author_id": 35899,
"author_profile": "https://wordpress.stackexchange.com/users/35899",
"pm_score": 1,
"selected": false,
"text": "<p>Few months ago I was working on a similar thing where I had to generate <a href=\"https://codex.wordpress.org/Shortcode\" rel=\"nofollow\">short codes</a> dynamically. But I took a different approach.</p>\n\n<p>What I did was as following;</p>\n\n<ol>\n<li><p>I registered a <a href=\"https://codex.wordpress.org/Shortcode\" rel=\"nofollow\">short code</a> and <a href=\"https://codex.wordpress.org/Post_Types#Custom_Post_Types\" rel=\"nofollow\">custom post type</a> for which I had to use that dynamic <a href=\"https://codex.wordpress.org/Shortcode\" rel=\"nofollow\">short code</a>.</p></li>\n<li><p>Then added <a href=\"https://codex.wordpress.org/Shortcode_API#Handling_Attributes\" rel=\"nofollow\">attribute</a> for <a href=\"http://codex.wordpress.org/Glossary#Post_Slug\" rel=\"nofollow\">post name (slug)</a> in that <a href=\"https://codex.wordpress.org/Shortcode\" rel=\"nofollow\">short code</a> to get data dynamically to display on front end.</p></li>\n</ol>\n\n<p>Here is sample code for how you can do that;</p>\n\n<pre><code>// Shortcode to display html in frontend\n// [dynamic_shortcode name='post-slug']\nfunction dynamic_shortcode( $atts ) {\n\n // Get Attributes\n extract( shortcode_atts(\n array(\n 'name' => '' // DEFAULT SLUG SET TO EMPTY\n ), $atts )\n );\n\n // WP_Query arguments\n $args = array (\n 'name' => $name, // GET POST BY SLUG // IGNORE IF YOU ARE GETTING ERROR ON THIS LINE IN YOUR EDITOR\n 'post_type' => 'your-post-type', // YOUR POST TYPE\n 'post_status' => 'publish', // POST STATUS\n );\n\n\n // The Query\n $query = new WP_Query( $args );\n\n // The Loop\n if ( $query->have_posts() && $name != '' ) {\n while ( $query->have_posts() ) {\n $query->the_post();\n\n $html_src = get_post_meta( get_the_ID() , 'html_src' , true); // GET HTML SOURCE FROM YOUR POST META\n\n if ( $html_src) {\n return $html_src; // RETURN HTML TO DISPLAY ON FRONT END\n }\n\n }\n } else {\n // no posts found\n return '<p style=\"color: red\" >Sorry You have set no html for this slug...</p>';\n\n }\n\n\n// Restore original Post Data\n wp_reset_postdata();\n}\nadd_shortcode( 'dynamic_shortcode', 'dynamic_shortcode' );\n</code></pre>\n\n<p>Hope this might work for you as well.</p>\n"
},
{
"answer_id": 196348,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 4,
"selected": true,
"text": "<p>the shortcodes doesn't shop up in the liste because it's not a valid declaration with a valid function callback on the 2nd argument</p>\n\n<p>try this to see what append : </p>\n\n<pre><code>// shortcode data\n\nadd_filter(\"shortcode_list\", function ($shortcode_list) {\n $shortcode_list[\"slugA\"] = array(\n \"html\" => \"test html 1\",\n );\n\n return $shortcode_list;\n});\n\nadd_filter(\"shortcode_list\", function ($shortcode_list) {\n $shortcode_list[\"slugB\"] = array(\n \"html\" => \"test <strong>html 2 - [slugA]</strong>\",\n );\n\n return $shortcode_list;\n});\n\n\n// shortcodes declaration\n\nadd_action(\"init\", function () {\n\n $shortcodes = apply_filters(\"shortcode_list\", array());\n\n foreach (array_keys($shortcodes) as $shortcode_slug) {\n add_shortcode($shortcode_slug, \"shortcode_callback\");\n };\n\n});\n\n\n// callback function\n\nfunction shortcode_callback($atts, $content = \"\", $tag) {\n\n // Build shortcode attributes.\n $atts = shortcode_atts( array(\n 'name' => 'john',\n 'type' => 'mammal'\n ), $atts);\n\n\n // shortcode data\n $shortcodes = apply_filters(\"shortcode_list\", array());\n $shortcode = $shortcodes[$tag];\n\n\n // construct result of the shortcode\n\n $markup = \"\";\n $markup .= '<div class=\"'.$atts['name'].'\">';\n $markup .= '<div>';\n // $shortcode should contain custom markup from the array.\n $markup .= $shortcode['html'];\n //$markup .= do_shortcode($shortcode['html']); // to replace shortcodes in the \"html\" data\n\n\n $markup .= '<pre>';\n $markup .= print_r($atts, TRUE);\n $markup .= '</pre>';\n\n $markup .= '</div>';\n $markup .= '</div>';\n\n return $markup;\n\n}\n</code></pre>\n"
}
] |
2015/08/01
|
[
"https://wordpress.stackexchange.com/questions/196339",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77128/"
] |
I am currently using the Minnow theme on Wordpress. I have set my site to show latest posts from my blog, but I have also create a page called 'About'. This page doesn't show up on my site or in the navigation menu and I'm not quite sure how to get this to display.
Would appreciate any help I can get.
Thank you.
|
the shortcodes doesn't shop up in the liste because it's not a valid declaration with a valid function callback on the 2nd argument
try this to see what append :
```
// shortcode data
add_filter("shortcode_list", function ($shortcode_list) {
$shortcode_list["slugA"] = array(
"html" => "test html 1",
);
return $shortcode_list;
});
add_filter("shortcode_list", function ($shortcode_list) {
$shortcode_list["slugB"] = array(
"html" => "test <strong>html 2 - [slugA]</strong>",
);
return $shortcode_list;
});
// shortcodes declaration
add_action("init", function () {
$shortcodes = apply_filters("shortcode_list", array());
foreach (array_keys($shortcodes) as $shortcode_slug) {
add_shortcode($shortcode_slug, "shortcode_callback");
};
});
// callback function
function shortcode_callback($atts, $content = "", $tag) {
// Build shortcode attributes.
$atts = shortcode_atts( array(
'name' => 'john',
'type' => 'mammal'
), $atts);
// shortcode data
$shortcodes = apply_filters("shortcode_list", array());
$shortcode = $shortcodes[$tag];
// construct result of the shortcode
$markup = "";
$markup .= '<div class="'.$atts['name'].'">';
$markup .= '<div>';
// $shortcode should contain custom markup from the array.
$markup .= $shortcode['html'];
//$markup .= do_shortcode($shortcode['html']); // to replace shortcodes in the "html" data
$markup .= '<pre>';
$markup .= print_r($atts, TRUE);
$markup .= '</pre>';
$markup .= '</div>';
$markup .= '</div>';
return $markup;
}
```
|
196,344 |
<p>I'm getting a post by id with get_post();</p>
<pre><code>$post = get_post(17);
$page = get_post_meta(17);
setup_postdata( $post );
include($page['_wp_page_template'][0]);
</code></pre>
<p>After getting the post I include a pagetemplate wich contains a:</p>
<pre><code>while ( have_posts() ) : the_post();
</code></pre>
<p>If I call <code>the_title()</code> from outside the loop I get the right title of the post called with get_post().
If I call <code>the_title()</code> from within the loop I get the title of the current page I'm on. How do I get the data from the <code>get_post</code> into the loop.</p>
|
[
{
"answer_id": 196350,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>There are multiple ways to handle these things and your question is a little light on detail <em>why</em> you need.</p>\n\n<p>Specific to the title part — to retrieve title of specific post you shouldn't be messing with globals at all, just do <code>$title = get_the_title( 17 );</code> or around that.</p>\n\n<p>In <em>most</em> of the cases template tags have a version that retrieves data for <em>specific</em> post, not just <em>current</em> post in the loop. There is also a lower level <code>get_post_field()</code> to retrieve raw or nearly raw data for the post.</p>\n"
},
{
"answer_id": 196373,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using <code>setup_postdata( $post )</code> you need to use the global <code>$post</code> as for some reason it does not work without that specific variable. Once you manually set <code>$post</code> to a new value, you are altering the <code>$post</code> global, so you will need to reset it back to the current post of the main query. </p>\n\n<p>Apart from that, you should never use any global variables set by Wordpress as a custom variable as this can cause non debuggable issues and unexpected results from your code. Breaking a global variable and then trying to debug such an issue will drive you up a mountain ;-)</p>\n\n<p>In your specific use case, you need to add <code>wp_reset_postdata()</code> immediately after your custom query is done</p>\n\n<pre><code>$post = get_post(17);\n$page_template = get_post_meta(17);\nsetup_postdata( $post ); \ninclude($page_template['_wp_page_template'][0]);\nwp_reset_postdata();\n</code></pre>\n"
}
] |
2015/08/01
|
[
"https://wordpress.stackexchange.com/questions/196344",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31706/"
] |
I'm getting a post by id with get\_post();
```
$post = get_post(17);
$page = get_post_meta(17);
setup_postdata( $post );
include($page['_wp_page_template'][0]);
```
After getting the post I include a pagetemplate wich contains a:
```
while ( have_posts() ) : the_post();
```
If I call `the_title()` from outside the loop I get the right title of the post called with get\_post().
If I call `the_title()` from within the loop I get the title of the current page I'm on. How do I get the data from the `get_post` into the loop.
|
If you are using `setup_postdata( $post )` you need to use the global `$post` as for some reason it does not work without that specific variable. Once you manually set `$post` to a new value, you are altering the `$post` global, so you will need to reset it back to the current post of the main query.
Apart from that, you should never use any global variables set by Wordpress as a custom variable as this can cause non debuggable issues and unexpected results from your code. Breaking a global variable and then trying to debug such an issue will drive you up a mountain ;-)
In your specific use case, you need to add `wp_reset_postdata()` immediately after your custom query is done
```
$post = get_post(17);
$page_template = get_post_meta(17);
setup_postdata( $post );
include($page_template['_wp_page_template'][0]);
wp_reset_postdata();
```
|
196,347 |
<p>I have read through a lot of responses on this site and am unable to find the issue with my code. </p>
<p>The form is : </p>
<pre><code><?php while (have_posts()) : the_post()?>
<form method='post' id="dav-international" >
<label for="dav-address">Address:</label><input type="text" name="dav-address" id="dav-address"/>
<button type="submit" id="submit">Submit</button>
</form>
<?php endwhile;?>
</code></pre>
<p>The functions are in <code>function.php</code> ( home-page is already enqueued ): </p>
<pre><code> add_action('wp_enqueue_scripts', 'dav_script');
function dav_script(){
if (is_front_page()){
$dav_nonce = wp_create_nonce('contact_form');
wp_localize_script('home-page', 'ajaxObj', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => $dav_nonce,
));
}
}
add_action('wp_ajax_nopriv_dav_validation', 'dav_form_validation');
add_action('wp_ajax_dav_validation', 'dav_form_validation');
function dav_form_validation(){
global $wpdb;
if ($_SERVER["REQUEST_METHOD"] == 'POST'){
check_ajax_referer('contact_form');
$dav_address = sanitize_text_field($_POST['info']);
$dav_ajax_data = array();
$dav_ajax_data['dav-address'] = $dav_address;
echo json_encode($dav_ajax_data);
}
wp_die();
}
</code></pre>
<p>and the jQuery is : </p>
<pre><code>var $j = jQuery;
$j('#submit').click(function(e){
var $j = jQuery;
e.preventDefault();
if ($j('#dav-address').val().length > 0){
var formInfo = $j('form').serialize();
var formdata = {
action : 'dav_validation',
_ajax_nonce: ajaxObj.nonce,
info : formInfo
}
$j.ajax({
type:'post',
url: ajaxObj.ajaxurl,
data: formdata,
success: function(data){
console.log(data);
}
})
}
});
</code></pre>
<p>I believe I followed the instructions on WordPress codex properly but the console continues to output 0. I am stuck on this and cannot seem to figure it out. </p>
|
[
{
"answer_id": 196350,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>There are multiple ways to handle these things and your question is a little light on detail <em>why</em> you need.</p>\n\n<p>Specific to the title part — to retrieve title of specific post you shouldn't be messing with globals at all, just do <code>$title = get_the_title( 17 );</code> or around that.</p>\n\n<p>In <em>most</em> of the cases template tags have a version that retrieves data for <em>specific</em> post, not just <em>current</em> post in the loop. There is also a lower level <code>get_post_field()</code> to retrieve raw or nearly raw data for the post.</p>\n"
},
{
"answer_id": 196373,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using <code>setup_postdata( $post )</code> you need to use the global <code>$post</code> as for some reason it does not work without that specific variable. Once you manually set <code>$post</code> to a new value, you are altering the <code>$post</code> global, so you will need to reset it back to the current post of the main query. </p>\n\n<p>Apart from that, you should never use any global variables set by Wordpress as a custom variable as this can cause non debuggable issues and unexpected results from your code. Breaking a global variable and then trying to debug such an issue will drive you up a mountain ;-)</p>\n\n<p>In your specific use case, you need to add <code>wp_reset_postdata()</code> immediately after your custom query is done</p>\n\n<pre><code>$post = get_post(17);\n$page_template = get_post_meta(17);\nsetup_postdata( $post ); \ninclude($page_template['_wp_page_template'][0]);\nwp_reset_postdata();\n</code></pre>\n"
}
] |
2015/08/01
|
[
"https://wordpress.stackexchange.com/questions/196347",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77130/"
] |
I have read through a lot of responses on this site and am unable to find the issue with my code.
The form is :
```
<?php while (have_posts()) : the_post()?>
<form method='post' id="dav-international" >
<label for="dav-address">Address:</label><input type="text" name="dav-address" id="dav-address"/>
<button type="submit" id="submit">Submit</button>
</form>
<?php endwhile;?>
```
The functions are in `function.php` ( home-page is already enqueued ):
```
add_action('wp_enqueue_scripts', 'dav_script');
function dav_script(){
if (is_front_page()){
$dav_nonce = wp_create_nonce('contact_form');
wp_localize_script('home-page', 'ajaxObj', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => $dav_nonce,
));
}
}
add_action('wp_ajax_nopriv_dav_validation', 'dav_form_validation');
add_action('wp_ajax_dav_validation', 'dav_form_validation');
function dav_form_validation(){
global $wpdb;
if ($_SERVER["REQUEST_METHOD"] == 'POST'){
check_ajax_referer('contact_form');
$dav_address = sanitize_text_field($_POST['info']);
$dav_ajax_data = array();
$dav_ajax_data['dav-address'] = $dav_address;
echo json_encode($dav_ajax_data);
}
wp_die();
}
```
and the jQuery is :
```
var $j = jQuery;
$j('#submit').click(function(e){
var $j = jQuery;
e.preventDefault();
if ($j('#dav-address').val().length > 0){
var formInfo = $j('form').serialize();
var formdata = {
action : 'dav_validation',
_ajax_nonce: ajaxObj.nonce,
info : formInfo
}
$j.ajax({
type:'post',
url: ajaxObj.ajaxurl,
data: formdata,
success: function(data){
console.log(data);
}
})
}
});
```
I believe I followed the instructions on WordPress codex properly but the console continues to output 0. I am stuck on this and cannot seem to figure it out.
|
If you are using `setup_postdata( $post )` you need to use the global `$post` as for some reason it does not work without that specific variable. Once you manually set `$post` to a new value, you are altering the `$post` global, so you will need to reset it back to the current post of the main query.
Apart from that, you should never use any global variables set by Wordpress as a custom variable as this can cause non debuggable issues and unexpected results from your code. Breaking a global variable and then trying to debug such an issue will drive you up a mountain ;-)
In your specific use case, you need to add `wp_reset_postdata()` immediately after your custom query is done
```
$post = get_post(17);
$page_template = get_post_meta(17);
setup_postdata( $post );
include($page_template['_wp_page_template'][0]);
wp_reset_postdata();
```
|
196,365 |
<p>Assuming I have a custom thumbnail size, as defined by the following...</p>
<pre><code>add_image_size( $name, $dim_x, $dim_y, true );
</code></pre>
<p>...how can I get the defined image dimensions programatically, using only $name ?</p>
|
[
{
"answer_id": 196350,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>There are multiple ways to handle these things and your question is a little light on detail <em>why</em> you need.</p>\n\n<p>Specific to the title part — to retrieve title of specific post you shouldn't be messing with globals at all, just do <code>$title = get_the_title( 17 );</code> or around that.</p>\n\n<p>In <em>most</em> of the cases template tags have a version that retrieves data for <em>specific</em> post, not just <em>current</em> post in the loop. There is also a lower level <code>get_post_field()</code> to retrieve raw or nearly raw data for the post.</p>\n"
},
{
"answer_id": 196373,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using <code>setup_postdata( $post )</code> you need to use the global <code>$post</code> as for some reason it does not work without that specific variable. Once you manually set <code>$post</code> to a new value, you are altering the <code>$post</code> global, so you will need to reset it back to the current post of the main query. </p>\n\n<p>Apart from that, you should never use any global variables set by Wordpress as a custom variable as this can cause non debuggable issues and unexpected results from your code. Breaking a global variable and then trying to debug such an issue will drive you up a mountain ;-)</p>\n\n<p>In your specific use case, you need to add <code>wp_reset_postdata()</code> immediately after your custom query is done</p>\n\n<pre><code>$post = get_post(17);\n$page_template = get_post_meta(17);\nsetup_postdata( $post ); \ninclude($page_template['_wp_page_template'][0]);\nwp_reset_postdata();\n</code></pre>\n"
}
] |
2015/08/01
|
[
"https://wordpress.stackexchange.com/questions/196365",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77143/"
] |
Assuming I have a custom thumbnail size, as defined by the following...
```
add_image_size( $name, $dim_x, $dim_y, true );
```
...how can I get the defined image dimensions programatically, using only $name ?
|
If you are using `setup_postdata( $post )` you need to use the global `$post` as for some reason it does not work without that specific variable. Once you manually set `$post` to a new value, you are altering the `$post` global, so you will need to reset it back to the current post of the main query.
Apart from that, you should never use any global variables set by Wordpress as a custom variable as this can cause non debuggable issues and unexpected results from your code. Breaking a global variable and then trying to debug such an issue will drive you up a mountain ;-)
In your specific use case, you need to add `wp_reset_postdata()` immediately after your custom query is done
```
$post = get_post(17);
$page_template = get_post_meta(17);
setup_postdata( $post );
include($page_template['_wp_page_template'][0]);
wp_reset_postdata();
```
|
196,368 |
<p>Does anyone know how to ad an item to the menu on the right side of the page.
Please see the photo attached.<a href="https://i.stack.imgur.com/hA229.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hA229.jpg" alt="enter image description here"></a></p>
<p>I basically want to add "ISSUES" as a menu item on the left side of page. Just like ARTIST is listed. I want to make this change and I dont know how to do it. Any help would be appreciated.</p>
<p>Hope it makes sense if not.</p>
|
[
{
"answer_id": 196350,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>There are multiple ways to handle these things and your question is a little light on detail <em>why</em> you need.</p>\n\n<p>Specific to the title part — to retrieve title of specific post you shouldn't be messing with globals at all, just do <code>$title = get_the_title( 17 );</code> or around that.</p>\n\n<p>In <em>most</em> of the cases template tags have a version that retrieves data for <em>specific</em> post, not just <em>current</em> post in the loop. There is also a lower level <code>get_post_field()</code> to retrieve raw or nearly raw data for the post.</p>\n"
},
{
"answer_id": 196373,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using <code>setup_postdata( $post )</code> you need to use the global <code>$post</code> as for some reason it does not work without that specific variable. Once you manually set <code>$post</code> to a new value, you are altering the <code>$post</code> global, so you will need to reset it back to the current post of the main query. </p>\n\n<p>Apart from that, you should never use any global variables set by Wordpress as a custom variable as this can cause non debuggable issues and unexpected results from your code. Breaking a global variable and then trying to debug such an issue will drive you up a mountain ;-)</p>\n\n<p>In your specific use case, you need to add <code>wp_reset_postdata()</code> immediately after your custom query is done</p>\n\n<pre><code>$post = get_post(17);\n$page_template = get_post_meta(17);\nsetup_postdata( $post ); \ninclude($page_template['_wp_page_template'][0]);\nwp_reset_postdata();\n</code></pre>\n"
}
] |
2015/08/02
|
[
"https://wordpress.stackexchange.com/questions/196368",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77145/"
] |
Does anyone know how to ad an item to the menu on the right side of the page.
Please see the photo attached.[](https://i.stack.imgur.com/hA229.jpg)
I basically want to add "ISSUES" as a menu item on the left side of page. Just like ARTIST is listed. I want to make this change and I dont know how to do it. Any help would be appreciated.
Hope it makes sense if not.
|
If you are using `setup_postdata( $post )` you need to use the global `$post` as for some reason it does not work without that specific variable. Once you manually set `$post` to a new value, you are altering the `$post` global, so you will need to reset it back to the current post of the main query.
Apart from that, you should never use any global variables set by Wordpress as a custom variable as this can cause non debuggable issues and unexpected results from your code. Breaking a global variable and then trying to debug such an issue will drive you up a mountain ;-)
In your specific use case, you need to add `wp_reset_postdata()` immediately after your custom query is done
```
$post = get_post(17);
$page_template = get_post_meta(17);
setup_postdata( $post );
include($page_template['_wp_page_template'][0]);
wp_reset_postdata();
```
|
196,376 |
<p><a href="https://wordpress.stackexchange.com/questions/180005/include-sticky-post-in-page-posts-count">This link</a> solves the problem but it's only for the main query. What if you are using a custom query? How can you <a href="https://wordpress.stackexchange.com/a/76639/73579">modify the answer</a> below:</p>
<pre><code>add_action('pre_get_posts', 'ad_custom_query');
function ad_custom_query($query) {
if ($query->is_main_query() && is_home()) { //how can we for specific custom query?
// set the number of posts per page
$posts_per_page = 12;
// get sticky posts array
$sticky_posts = get_option( 'sticky_posts' );
// if we have any sticky posts and we are at the first page
if (is_array($sticky_posts) && !$query->is_paged()) {
// counnt the number of sticky posts
$sticky_count = count($sticky_posts);
// and if the number of sticky posts is less than
// the number we want to set:
if ($sticky_count < $posts_per_page) {
$query->set('posts_per_page', $posts_per_page - $sticky_count);
// if the number of sticky posts is greater than or equal
// the number of pages we want to set:
} else {
$query->set('posts_per_page', 1);
}
// fallback in case we have no sticky posts
// and we are not on the first page
} else {
$query->set('posts_per_page', $posts_per_page);
}
}
}
</code></pre>
|
[
{
"answer_id": 196350,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>There are multiple ways to handle these things and your question is a little light on detail <em>why</em> you need.</p>\n\n<p>Specific to the title part — to retrieve title of specific post you shouldn't be messing with globals at all, just do <code>$title = get_the_title( 17 );</code> or around that.</p>\n\n<p>In <em>most</em> of the cases template tags have a version that retrieves data for <em>specific</em> post, not just <em>current</em> post in the loop. There is also a lower level <code>get_post_field()</code> to retrieve raw or nearly raw data for the post.</p>\n"
},
{
"answer_id": 196373,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using <code>setup_postdata( $post )</code> you need to use the global <code>$post</code> as for some reason it does not work without that specific variable. Once you manually set <code>$post</code> to a new value, you are altering the <code>$post</code> global, so you will need to reset it back to the current post of the main query. </p>\n\n<p>Apart from that, you should never use any global variables set by Wordpress as a custom variable as this can cause non debuggable issues and unexpected results from your code. Breaking a global variable and then trying to debug such an issue will drive you up a mountain ;-)</p>\n\n<p>In your specific use case, you need to add <code>wp_reset_postdata()</code> immediately after your custom query is done</p>\n\n<pre><code>$post = get_post(17);\n$page_template = get_post_meta(17);\nsetup_postdata( $post ); \ninclude($page_template['_wp_page_template'][0]);\nwp_reset_postdata();\n</code></pre>\n"
}
] |
2015/08/02
|
[
"https://wordpress.stackexchange.com/questions/196376",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
[This link](https://wordpress.stackexchange.com/questions/180005/include-sticky-post-in-page-posts-count) solves the problem but it's only for the main query. What if you are using a custom query? How can you [modify the answer](https://wordpress.stackexchange.com/a/76639/73579) below:
```
add_action('pre_get_posts', 'ad_custom_query');
function ad_custom_query($query) {
if ($query->is_main_query() && is_home()) { //how can we for specific custom query?
// set the number of posts per page
$posts_per_page = 12;
// get sticky posts array
$sticky_posts = get_option( 'sticky_posts' );
// if we have any sticky posts and we are at the first page
if (is_array($sticky_posts) && !$query->is_paged()) {
// counnt the number of sticky posts
$sticky_count = count($sticky_posts);
// and if the number of sticky posts is less than
// the number we want to set:
if ($sticky_count < $posts_per_page) {
$query->set('posts_per_page', $posts_per_page - $sticky_count);
// if the number of sticky posts is greater than or equal
// the number of pages we want to set:
} else {
$query->set('posts_per_page', 1);
}
// fallback in case we have no sticky posts
// and we are not on the first page
} else {
$query->set('posts_per_page', $posts_per_page);
}
}
}
```
|
If you are using `setup_postdata( $post )` you need to use the global `$post` as for some reason it does not work without that specific variable. Once you manually set `$post` to a new value, you are altering the `$post` global, so you will need to reset it back to the current post of the main query.
Apart from that, you should never use any global variables set by Wordpress as a custom variable as this can cause non debuggable issues and unexpected results from your code. Breaking a global variable and then trying to debug such an issue will drive you up a mountain ;-)
In your specific use case, you need to add `wp_reset_postdata()` immediately after your custom query is done
```
$post = get_post(17);
$page_template = get_post_meta(17);
setup_postdata( $post );
include($page_template['_wp_page_template'][0]);
wp_reset_postdata();
```
|
196,394 |
<p>Is it possible, with <code>WP_Query</code>, to get all posts which have at least one category or custom taxonomy term set?</p>
|
[
{
"answer_id": 196409,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, totally possible. </p>\n\n<h2>SCENARIO 1</h2>\n\n<p>If you need only one taxonomy, all you need to do is to get all the term ID's of all terms assigned to the taxonomy and then pass that array of term ID's to a <code>tax_query</code></p>\n\n<p>(<em>Requires PHP5.4+</em>)</p>\n\n<pre><code>$term_ids = get_terms( \n 'TAXONOMY_NAME', \n [ // Array of arguments, see get_terms()\n 'fields' => 'ids' // Get only term ids to make query lean\n ]\n);\nif ( $term_ids // Check if we have terms\n && !is_wp_error( $term_ids ) // Check for no WP_Error object\n) {\n $args = [\n 'tax_query' => [\n [\n 'taxonomy' => 'TAXONOMY_NAME',\n 'terms' => $term_ids,\n ]\n ],\n ];\n $q = new WP_Query( $args );\n\n // Run your loop as needed. Remeber wp_reset_postdata() after the query\n}\n</code></pre>\n\n<h2>SCENARIO 2</h2>\n\n<p>If you need posts that should have terms assigned to multiple taxonomies, you can build a more complex query on the logic of <strong><em>SCENARIO 1</em></strong></p>\n\n<pre><code>$taxonomies = ['TAXONOMY_NAME_1', 'TAXONOMY_NAME_2']; // Array of taxonomies, can also use get_taxonomies for all\n$tax_array = []; // Set the variable to hold our tax query array values\nforeach ( $taxonomies as $key=>$taxonomy ) {\n\n $term_ids = get_terms( \n $taxonomy, \n [ // Array of arguments, see get_terms()\n 'fields' => 'ids' // Get only term ids to make query lean\n ]\n );\n if ( $term_ids // Check if we have terms\n && !is_wp_error( $term_ids ) // Check for no WP_Error object\n ) {\n $tax_array[$key] = [\n 'taxonomy' => $taxonomy,\n 'terms' => $term_ids,\n ];\n }\n}\n$relation = 'OR'; // Set the tax_query relation, we will use OR\nif ( $tax_array ) { // Check if we have a valid array \n if ( count( $tax_array ) == 1 ) {\n $tax_query[] = $tax_array;\n } else {\n $tax_query = [\n 'relation' => $relation,\n $tax_array\n ];\n }\n\n $args = [ // Set query arguments\n 'tax_query' => $tax_query,\n // Any other query arguments that you might want to add\n ]; \n $q = new WP_Query( $args );\n\n // Run your loop as needed. Remeber wp_reset_postdata() after the query\n}\n</code></pre>\n"
},
{
"answer_id": 384391,
"author": "Ahmed El-Atab",
"author_id": 182181,
"author_profile": "https://wordpress.stackexchange.com/users/182181",
"pm_score": 2,
"selected": false,
"text": "<p><strong>UPDATE:</strong></p>\n<p><code>get_terms()</code> now takes an array like this:</p>\n<pre><code>$terms = get_terms( array(\n 'taxonomy' => 'post_tag',\n 'hide_empty' => false,\n) );\n</code></pre>\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_terms\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_terms</a></p>\n"
}
] |
2015/08/02
|
[
"https://wordpress.stackexchange.com/questions/196394",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13205/"
] |
Is it possible, with `WP_Query`, to get all posts which have at least one category or custom taxonomy term set?
|
Yes, totally possible.
SCENARIO 1
----------
If you need only one taxonomy, all you need to do is to get all the term ID's of all terms assigned to the taxonomy and then pass that array of term ID's to a `tax_query`
(*Requires PHP5.4+*)
```
$term_ids = get_terms(
'TAXONOMY_NAME',
[ // Array of arguments, see get_terms()
'fields' => 'ids' // Get only term ids to make query lean
]
);
if ( $term_ids // Check if we have terms
&& !is_wp_error( $term_ids ) // Check for no WP_Error object
) {
$args = [
'tax_query' => [
[
'taxonomy' => 'TAXONOMY_NAME',
'terms' => $term_ids,
]
],
];
$q = new WP_Query( $args );
// Run your loop as needed. Remeber wp_reset_postdata() after the query
}
```
SCENARIO 2
----------
If you need posts that should have terms assigned to multiple taxonomies, you can build a more complex query on the logic of ***SCENARIO 1***
```
$taxonomies = ['TAXONOMY_NAME_1', 'TAXONOMY_NAME_2']; // Array of taxonomies, can also use get_taxonomies for all
$tax_array = []; // Set the variable to hold our tax query array values
foreach ( $taxonomies as $key=>$taxonomy ) {
$term_ids = get_terms(
$taxonomy,
[ // Array of arguments, see get_terms()
'fields' => 'ids' // Get only term ids to make query lean
]
);
if ( $term_ids // Check if we have terms
&& !is_wp_error( $term_ids ) // Check for no WP_Error object
) {
$tax_array[$key] = [
'taxonomy' => $taxonomy,
'terms' => $term_ids,
];
}
}
$relation = 'OR'; // Set the tax_query relation, we will use OR
if ( $tax_array ) { // Check if we have a valid array
if ( count( $tax_array ) == 1 ) {
$tax_query[] = $tax_array;
} else {
$tax_query = [
'relation' => $relation,
$tax_array
];
}
$args = [ // Set query arguments
'tax_query' => $tax_query,
// Any other query arguments that you might want to add
];
$q = new WP_Query( $args );
// Run your loop as needed. Remeber wp_reset_postdata() after the query
}
```
|
196,412 |
<p>I'm currently developing a non-trivial theme right now, most of the time I'm not using <a href="https://developer.wordpress.org/reference/functions/__/" rel="nofollow">a <code>__($str)</code> translate function</a> when there's an HTML tag therein the text. Is it good to always use the translate functions such <code>__($str)</code> and <code>_e($str)</code> whenever there's a text that'll be going to output? Any downside with it?</p>
<p>Can I still use it even to a very long text that have mixed with an HTML tag such like this?</p>
<pre><code>__("This <em>text</em> have an <b>HTML</b> tag. Another sentence...")
</code></pre>
<p>Or it is good to use like this? <em>(*Looks messy..)</em></p>
<pre><code>__('This ').'<em>'.__('text').'</em>'.' have an '.'<b>'.__('HTML').'</b>'__(' tag.')
</code></pre>
<p>How to properly use such kind of a function?</p>
|
[
{
"answer_id": 196409,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, totally possible. </p>\n\n<h2>SCENARIO 1</h2>\n\n<p>If you need only one taxonomy, all you need to do is to get all the term ID's of all terms assigned to the taxonomy and then pass that array of term ID's to a <code>tax_query</code></p>\n\n<p>(<em>Requires PHP5.4+</em>)</p>\n\n<pre><code>$term_ids = get_terms( \n 'TAXONOMY_NAME', \n [ // Array of arguments, see get_terms()\n 'fields' => 'ids' // Get only term ids to make query lean\n ]\n);\nif ( $term_ids // Check if we have terms\n && !is_wp_error( $term_ids ) // Check for no WP_Error object\n) {\n $args = [\n 'tax_query' => [\n [\n 'taxonomy' => 'TAXONOMY_NAME',\n 'terms' => $term_ids,\n ]\n ],\n ];\n $q = new WP_Query( $args );\n\n // Run your loop as needed. Remeber wp_reset_postdata() after the query\n}\n</code></pre>\n\n<h2>SCENARIO 2</h2>\n\n<p>If you need posts that should have terms assigned to multiple taxonomies, you can build a more complex query on the logic of <strong><em>SCENARIO 1</em></strong></p>\n\n<pre><code>$taxonomies = ['TAXONOMY_NAME_1', 'TAXONOMY_NAME_2']; // Array of taxonomies, can also use get_taxonomies for all\n$tax_array = []; // Set the variable to hold our tax query array values\nforeach ( $taxonomies as $key=>$taxonomy ) {\n\n $term_ids = get_terms( \n $taxonomy, \n [ // Array of arguments, see get_terms()\n 'fields' => 'ids' // Get only term ids to make query lean\n ]\n );\n if ( $term_ids // Check if we have terms\n && !is_wp_error( $term_ids ) // Check for no WP_Error object\n ) {\n $tax_array[$key] = [\n 'taxonomy' => $taxonomy,\n 'terms' => $term_ids,\n ];\n }\n}\n$relation = 'OR'; // Set the tax_query relation, we will use OR\nif ( $tax_array ) { // Check if we have a valid array \n if ( count( $tax_array ) == 1 ) {\n $tax_query[] = $tax_array;\n } else {\n $tax_query = [\n 'relation' => $relation,\n $tax_array\n ];\n }\n\n $args = [ // Set query arguments\n 'tax_query' => $tax_query,\n // Any other query arguments that you might want to add\n ]; \n $q = new WP_Query( $args );\n\n // Run your loop as needed. Remeber wp_reset_postdata() after the query\n}\n</code></pre>\n"
},
{
"answer_id": 384391,
"author": "Ahmed El-Atab",
"author_id": 182181,
"author_profile": "https://wordpress.stackexchange.com/users/182181",
"pm_score": 2,
"selected": false,
"text": "<p><strong>UPDATE:</strong></p>\n<p><code>get_terms()</code> now takes an array like this:</p>\n<pre><code>$terms = get_terms( array(\n 'taxonomy' => 'post_tag',\n 'hide_empty' => false,\n) );\n</code></pre>\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_terms\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_terms</a></p>\n"
}
] |
2015/08/02
|
[
"https://wordpress.stackexchange.com/questions/196412",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73330/"
] |
I'm currently developing a non-trivial theme right now, most of the time I'm not using [a `__($str)` translate function](https://developer.wordpress.org/reference/functions/__/) when there's an HTML tag therein the text. Is it good to always use the translate functions such `__($str)` and `_e($str)` whenever there's a text that'll be going to output? Any downside with it?
Can I still use it even to a very long text that have mixed with an HTML tag such like this?
```
__("This <em>text</em> have an <b>HTML</b> tag. Another sentence...")
```
Or it is good to use like this? *(\*Looks messy..)*
```
__('This ').'<em>'.__('text').'</em>'.' have an '.'<b>'.__('HTML').'</b>'__(' tag.')
```
How to properly use such kind of a function?
|
Yes, totally possible.
SCENARIO 1
----------
If you need only one taxonomy, all you need to do is to get all the term ID's of all terms assigned to the taxonomy and then pass that array of term ID's to a `tax_query`
(*Requires PHP5.4+*)
```
$term_ids = get_terms(
'TAXONOMY_NAME',
[ // Array of arguments, see get_terms()
'fields' => 'ids' // Get only term ids to make query lean
]
);
if ( $term_ids // Check if we have terms
&& !is_wp_error( $term_ids ) // Check for no WP_Error object
) {
$args = [
'tax_query' => [
[
'taxonomy' => 'TAXONOMY_NAME',
'terms' => $term_ids,
]
],
];
$q = new WP_Query( $args );
// Run your loop as needed. Remeber wp_reset_postdata() after the query
}
```
SCENARIO 2
----------
If you need posts that should have terms assigned to multiple taxonomies, you can build a more complex query on the logic of ***SCENARIO 1***
```
$taxonomies = ['TAXONOMY_NAME_1', 'TAXONOMY_NAME_2']; // Array of taxonomies, can also use get_taxonomies for all
$tax_array = []; // Set the variable to hold our tax query array values
foreach ( $taxonomies as $key=>$taxonomy ) {
$term_ids = get_terms(
$taxonomy,
[ // Array of arguments, see get_terms()
'fields' => 'ids' // Get only term ids to make query lean
]
);
if ( $term_ids // Check if we have terms
&& !is_wp_error( $term_ids ) // Check for no WP_Error object
) {
$tax_array[$key] = [
'taxonomy' => $taxonomy,
'terms' => $term_ids,
];
}
}
$relation = 'OR'; // Set the tax_query relation, we will use OR
if ( $tax_array ) { // Check if we have a valid array
if ( count( $tax_array ) == 1 ) {
$tax_query[] = $tax_array;
} else {
$tax_query = [
'relation' => $relation,
$tax_array
];
}
$args = [ // Set query arguments
'tax_query' => $tax_query,
// Any other query arguments that you might want to add
];
$q = new WP_Query( $args );
// Run your loop as needed. Remeber wp_reset_postdata() after the query
}
```
|
196,449 |
<p>I am currently building a wordpress plugin to send email notification to list of users roles who comments on a post.</p>
<p><strong>For Example:</strong></p>
<p>If a user with "subscriber" role comments on a post all the other users who have "subscriber" role gets email alert.Currently i have achieved this through the following code</p>
<pre><code>if( current_user_can('subscriber'))
{
$user_query = new WP_User_Query( array( 'role' => 'subscriber');
foreach ( $user_query->results as $user )
{
$mail=$user->user_email;
$subject ="this is example";
$message = "";
$message .= "$post_permalink\n";
wp_mail($user->user_email, $subject,$message);
}
}
</code></pre>
<p>The above code sends email to all the users who have "subscriber" role.</p>
<p><strong>Output:</strong></p>
<p>It gets even the current user who comments on the post and send the email notification.</p>
<p><strong>Problem to be solved:</strong></p>
<p>How can i exclude the current user email and send only notification to other users those who have "subscriber" role .</p>
|
[
{
"answer_id": 196451,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": -1,
"selected": false,
"text": "<p>Following should works for you:- </p>\n\n<pre><code> if( current_user_can('read')) { \n $exclude_user = array();\n $exclude_user[] =get_current_user_id();\n $args = array(\n 'role' => 'subscriber',\n 'exclude' => $exclude_user\n );\n $user_query = new WP_User_Query( $args); \n foreach ( $user_query->results as $user ) { $mail=$user->user_email;\n\n $subject =\"this is example\";\n $message = \"\";\n $message .= \"$post_permalink\\n\";\n\n wp_mail($user->user_email, $subject,$message); \n }\n\n\n}\n</code></pre>\n"
},
{
"answer_id": 196455,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": true,
"text": "<p>First, you should know that <a href=\"https://codex.wordpress.org/Function_Reference/current_user_can\" rel=\"nofollow\"><code>current_user_can()</code></a> only accepts capabilities, not roles, so you are using it wrong and you can end up with unexpected results.</p>\n\n<p>That being said, to exlude users form <code>WP_User_Query</code> you can use the <a href=\"https://codex.wordpress.org/Class_Reference/WP_User_Query#Include_.26_Exclude_Parameters\" rel=\"nofollow\">exclude parameter</a>:</p>\n\n<pre><code>// Get current user data\n$user = wp_get_current_user();\n\n// Check if current user is a subscriber\nif( ! empty( $user ) && in_array( \"subscriber\", (array) $user->roles ) ) {\n\n $user_query = new WP_User_Query( array(\n 'role' => 'subscriber',\n // exlude current user\n 'exclude' => array( $user->ID ),\n )\n );\n\n $subscribers = $user_query->get_results();\n\n if( ! empty( $subscribers ) ) {\n foreach ( $subscribers as $user ) {\n\n $mail = $user->user_email;\n $subject =\"this is example\";\n $message = \"\";\n $message .= \"$post_permalink\\n\";\n\n wp_mail( $mail, $subject, $message);\n\n }\n }\n\n}\n</code></pre>\n"
}
] |
2015/08/03
|
[
"https://wordpress.stackexchange.com/questions/196449",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74004/"
] |
I am currently building a wordpress plugin to send email notification to list of users roles who comments on a post.
**For Example:**
If a user with "subscriber" role comments on a post all the other users who have "subscriber" role gets email alert.Currently i have achieved this through the following code
```
if( current_user_can('subscriber'))
{
$user_query = new WP_User_Query( array( 'role' => 'subscriber');
foreach ( $user_query->results as $user )
{
$mail=$user->user_email;
$subject ="this is example";
$message = "";
$message .= "$post_permalink\n";
wp_mail($user->user_email, $subject,$message);
}
}
```
The above code sends email to all the users who have "subscriber" role.
**Output:**
It gets even the current user who comments on the post and send the email notification.
**Problem to be solved:**
How can i exclude the current user email and send only notification to other users those who have "subscriber" role .
|
First, you should know that [`current_user_can()`](https://codex.wordpress.org/Function_Reference/current_user_can) only accepts capabilities, not roles, so you are using it wrong and you can end up with unexpected results.
That being said, to exlude users form `WP_User_Query` you can use the [exclude parameter](https://codex.wordpress.org/Class_Reference/WP_User_Query#Include_.26_Exclude_Parameters):
```
// Get current user data
$user = wp_get_current_user();
// Check if current user is a subscriber
if( ! empty( $user ) && in_array( "subscriber", (array) $user->roles ) ) {
$user_query = new WP_User_Query( array(
'role' => 'subscriber',
// exlude current user
'exclude' => array( $user->ID ),
)
);
$subscribers = $user_query->get_results();
if( ! empty( $subscribers ) ) {
foreach ( $subscribers as $user ) {
$mail = $user->user_email;
$subject ="this is example";
$message = "";
$message .= "$post_permalink\n";
wp_mail( $mail, $subject, $message);
}
}
}
```
|
196,453 |
<p>I'm using Wordpress with UserPro, and want my menu to display the logged-in user's first name, linked to the user profile page.</p>
<p>The problem is that in my menu structure, the "Profile" menu option is supposed to have a sub-menu containing "edit profile", "submit", and "logout".</p>
<p>This is the code I'm currently using:</p>
<pre><code>/*earlier code, currently commented out, for function to
display username in menu using #profile_name# placeholder
function give_profile_name($atts){
echo userpro_profile_data('first_name', get_current_user_id());
}
add_shortcode('profile_name', 'give_profile_name');
add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items' );
function my_dynamic_menu_items( $menu_items ) {
foreach ( $menu_items as $menu_item ) {
if ( '#profile_name#' == $menu_item->title ) {
global $shortcode_tags;
if ( isset( $shortcode_tags['profile_name'] ) ) {
// Or do_shortcode(), if you must.
$menu_item->title = call_user_func( $shortcode_tags['profile_name'] );
}
}
}
return $menu_items;
}
end of earlier code */
//currently in use, unlinked code
add_filter( 'wp_nav_menu_items', 'my_custom_menu_item');
function my_custom_menu_item($items)
{
if(is_user_logged_in())
{
$user=wp_get_current_user();
$name=$user->user_firstname;
$items .= '<li>'.$name.'';
}
return $items;
}
</code></pre>
<p>I can fiddle around and try to add the sub-menu under the menu by fiddling with the code from Firebug, but that would mean manual edits to all the links in the functions.php, which would be tedious.</p>
<p>I want to be able to add, edit, remove, and redirect the sub-menu items easily via the Wordpress menu.</p>
<p>Please advise.</p>
|
[
{
"answer_id": 196467,
"author": "Akash kapur",
"author_id": 76819,
"author_profile": "https://wordpress.stackexchange.com/users/76819",
"pm_score": 4,
"selected": true,
"text": "<p>Okay, I found a solution (and it can be used for any theme, with any plugin as it only uses core WordPress functions).</p>\n\n<p>In the menu, name the menu item where you want the user's name to appear with a place-holder (see screenshot below). Example: #profile_name#, #user#, #random# </p>\n\n<p><a href=\"https://i.stack.imgur.com/oxQor.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/oxQor.png\" alt=\"enter image description here\"></a></p>\n\n<p>Now, add the following code to the your child-theme's functions.php:</p>\n\n<pre><code>function give_profile_name($atts){\n $user=wp_get_current_user();\n $name=$user->user_firstname; \n return $name;\n}\n\nadd_shortcode('profile_name', 'give_profile_name');\n\nadd_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items' );\nfunction my_dynamic_menu_items( $menu_items ) {\n foreach ( $menu_items as $menu_item ) {\n if ( '#profile_name#' == $menu_item->title ) {\n global $shortcode_tags;\n if ( isset( $shortcode_tags['profile_name'] ) ) {\n // Or do_shortcode(), if you must.\n $menu_item->title = call_user_func( $shortcode_tags['profile_name'] );\n } \n }\n }\n\n return $menu_items;\n} \n</code></pre>\n\n<p>In case you're using your own place-holder, remember to replace #profile_name# with the name of your custom place-holder in the code above.</p>\n\n<p>Apologies in case I've misused the term 'place-holder'.</p>\n"
},
{
"answer_id": 244108,
"author": "Eutychus Mak",
"author_id": 105767,
"author_profile": "https://wordpress.stackexchange.com/users/105767",
"pm_score": 3,
"selected": false,
"text": "<p>The code:</p>\n\n<pre><code>function give_profile_name($atts){\n...\n}\n</code></pre>\n\n<p>gives a warning. Better is:</p>\n\n<pre><code>function give_profile_name(){\n...\n}\n</code></pre>\n\n<p>And it is better to detect if the user is logged in or not. Like so:</p>\n\n<pre><code>function give_profile_name(){\n $user=wp_get_current_user();\n if(!is_user_logged_in())\n $name = \"User not logged in\";\n else\n $name=$user->user_firstname.' '.$user->user_lastname; \n return $name;\n}\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 292057,
"author": "Manu Lebranders",
"author_id": 135475,
"author_profile": "https://wordpress.stackexchange.com/users/135475",
"pm_score": 3,
"selected": false,
"text": "<p>No shortcode needed</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items' );\nfunction my_dynamic_menu_items( $menu_items ) {\n foreach ( $menu_items as $menu_item ) {\n if ( strpos($menu_item->title, '#profile_name#') !== false) {\n $menu_item->title = str_replace(\"#profile_name#\", wp_get_current_user()->user_firstname, $menu_item->title);\n }\n }\n\n return $menu_items;\n} \n</code></pre>\n"
}
] |
2015/08/03
|
[
"https://wordpress.stackexchange.com/questions/196453",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76819/"
] |
I'm using Wordpress with UserPro, and want my menu to display the logged-in user's first name, linked to the user profile page.
The problem is that in my menu structure, the "Profile" menu option is supposed to have a sub-menu containing "edit profile", "submit", and "logout".
This is the code I'm currently using:
```
/*earlier code, currently commented out, for function to
display username in menu using #profile_name# placeholder
function give_profile_name($atts){
echo userpro_profile_data('first_name', get_current_user_id());
}
add_shortcode('profile_name', 'give_profile_name');
add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items' );
function my_dynamic_menu_items( $menu_items ) {
foreach ( $menu_items as $menu_item ) {
if ( '#profile_name#' == $menu_item->title ) {
global $shortcode_tags;
if ( isset( $shortcode_tags['profile_name'] ) ) {
// Or do_shortcode(), if you must.
$menu_item->title = call_user_func( $shortcode_tags['profile_name'] );
}
}
}
return $menu_items;
}
end of earlier code */
//currently in use, unlinked code
add_filter( 'wp_nav_menu_items', 'my_custom_menu_item');
function my_custom_menu_item($items)
{
if(is_user_logged_in())
{
$user=wp_get_current_user();
$name=$user->user_firstname;
$items .= '<li>'.$name.'';
}
return $items;
}
```
I can fiddle around and try to add the sub-menu under the menu by fiddling with the code from Firebug, but that would mean manual edits to all the links in the functions.php, which would be tedious.
I want to be able to add, edit, remove, and redirect the sub-menu items easily via the Wordpress menu.
Please advise.
|
Okay, I found a solution (and it can be used for any theme, with any plugin as it only uses core WordPress functions).
In the menu, name the menu item where you want the user's name to appear with a place-holder (see screenshot below). Example: #profile\_name#, #user#, #random#
[](https://i.stack.imgur.com/oxQor.png)
Now, add the following code to the your child-theme's functions.php:
```
function give_profile_name($atts){
$user=wp_get_current_user();
$name=$user->user_firstname;
return $name;
}
add_shortcode('profile_name', 'give_profile_name');
add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items' );
function my_dynamic_menu_items( $menu_items ) {
foreach ( $menu_items as $menu_item ) {
if ( '#profile_name#' == $menu_item->title ) {
global $shortcode_tags;
if ( isset( $shortcode_tags['profile_name'] ) ) {
// Or do_shortcode(), if you must.
$menu_item->title = call_user_func( $shortcode_tags['profile_name'] );
}
}
}
return $menu_items;
}
```
In case you're using your own place-holder, remember to replace #profile\_name# with the name of your custom place-holder in the code above.
Apologies in case I've misused the term 'place-holder'.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.